🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 解构赋值 ### 对象解构和数组解构的不同之处 - 数组解构若出现缺省需要解构占位 ``` let [,,x] = [1,2,3]; //而对象解构因为存在键名所以不需要 ``` - 数组解构和对象解构都可以设置默认值,另外对象解构可以设置别名 >[danger] **注意**:等号为默认值,冒号为取别名 ``` let [a = "a", b = "b", c =new Error('C必须指定')] = [1, , 3]; //用冒号给对象的键名取个别名,且原先名字不再能用 let {name:diyName} = {name:'abc'}; console.log(diyName); //abc //对象解构默认值 s({}); //1 function s({a='1',b='2',c='3'}){ console.log(a); //1 } let {a=1,b=2,c=3} = {}; console.log(a); //1 console.log(b); //2 //数组成员木有键名,数组解构相当于就是给成员取了个别名 let [a,b,c] = [1,2,3]; console.log(a); //1 console.log(b); //2 ``` ### 解构参数 ``` let destruct = function({name,age}){ console.log(name,age); } destruct({name:'ff',age:1}); ``` ### 嵌套赋值 重点在于神似 ``` let [x, [y], z] = [1, [2.1, 2.2]]; console.log(x, y, z); let [x, [y,z]] = [1, [2.1, 2.2]]; console.log(x,y,z); let [json,arr,num] = [{name:'ff'},[1,2],3]; console.log(json,arr,num); ``` ### 基本类型的结构赋值 ``` let {length:len} = 'hello'; //String.prototype.length console.log(len); //5 let [a,b,c,d] = '1234'; console.log(a,b,c,d); //1 2 3 4 let {toString:ts} = 1; let {toString:ts2} = true; console.log(ts); //function toString(){[natvie code]} console.log(ts2); //function toString(){[natvie code]} //Num.prototype.toString ``` ## 展开操作符 ``` // 可以替代concat var arr1 = [1, 3]; var arr2 = [3, 5]; var arr3 = arr1.concat(arr2); var arr4 = [...arr1, ...arr2]; // 可以替代apply var m1 = Math.max.apply(null, [8, 9, 4, 1]); var m2 = Math.max(...[8, 9, 4, 1]); //传入参数 let print = function(a,b,c){ console.log(a,b,c); } // print([1,2,3]); print(...[1,2,3]); //类数组的转数组 function max(a,b,c) { console.log(Math.max(...arguments)); } max(1, 3, 4); ``` ## 剩余运算符 剩余操作符可以把其余的参数的值都放到数组里面 ``` let rest = function(a,...rest){ console.log(a,rest); } rest(1,2,3); ```