目录
1.数组解构 等号左边的变量放到中括号内部,匹配右侧数组中的元素。
1.1完全解构:
- let [a,b,c,[d],e]=[1,2,3,[4,5,6],7];
- console.log(a,b,c,d,e)
-
- //1 2 3 4 7
- let [a,b,c,d,e]=[1,2,3,4];
- console.log(a,b,c,d,e);
-
- //1 2 3 4 undefined
- let [a,b,c,d,e]=[1,2,3,[4,5],6];
- console.log(a,b,c,d,e);
-
- //1 2 3 [ 4, 5 ] 6
1.2不完全解构
- let [a,b,c,[d],e]=[1,2,3,[4,5,6],7];
- console.log(a,b,c,d,e);
-
- //1 2 3 4 7
1.3默认值解构 默认值生效条件 当右侧匹配严格模式为undefiend
- let [a=1,b=2,c=3]=[4,5,6];
- console.log(a,b,c);
-
- //4 5 6
-
-
- let [a=1,b=2,c=3]=[];
- console.log(a,b,c);
-
- //1 2 3
默认值也可以是一个函数
- let test=()=>{
- console.log('我是箭头函数');
- return 1
- }
- let [a=test()]=[];
- console.log(a);
-
- //我是箭头函数
- //1
-
-
-
- let test=()=>{
- console.log('我是箭头函数');
- return 1
- }
- let [a=test()]=[222];
- console.log(a);
-
-
- //222
1.4集合解构 拓展运算符
- let [a,...b]=[1,2,3,4];
- console.log(a,b);
-
- //1 [ 2, 3, 4 ]
15.拓展运算符
- let a=[1,2,3,4,5];
- let [...arr]=a;
- console.log(arr);
- console.log(arr===a);
-
-
- //[ 1, 2, 3, 4, 5 ]
- //false
2.1属性名必须和变量名一致才能取到正确的值
- let {name,age}={name:'lili',age:18};
- console.log(name,age);
-
- //lili 18
2.2属性名和变量名不一致 给属性名重命名
- let {name:a,age:b}={name:'lili',age:12};
- console.log(a,b);
-
- //lili 12
2.3嵌套结构
- let obj={p:['hello',{y:"world"}]};// a b取到hello world
- let {p:[a,{y:b}]}=obj;
- console.log(a,b);
-
-
- //hello world
2.4对象默认值结构
- let {x:y=888}={};
- console.log(y);
-
- //888
练习题:
- const [a, b, c, ...d] = [1, 2, 3, 11, 999];
- const { e, f,f1, g, ...h } = { f: 4, g: 5, i: 6, j: 7 };
- console.log(a, b, c, d, e, f1, g, h);
-
-
- //1 2 3 [ 11, 999 ] undefined undefined 5 { i: 6, j: 7 }
可以使用对象解构或者是数组解构,使用数组结构可以获取指定字符;使用对象结构可以获取实例属性方法;
3.1.使用数组进行字符串解构
- let [a,b,c,d,e]='hello';
- console.log(a,b,c,d,e);
-
- //h e l l o
3.2.使用拓展运算符 解构字符串
- let [...arr]='world';
- console.log(arr);
-
- //[ 'w', 'o', 'r', 'l', 'd' ]
3.3使用对象解构字符串
- //String.prototype.toString/valueOf/length
- let {toString,valueOf,length}='hello';
- console.log(toString,valueOf,length);
-
-
- //[ 'w', 'o', 'r', 'l', 'd' ]
- //[Function: toString] [Function: valueOf] 5
- let {toString,valueOf}=10;
- console.log(toString,valueOf)
-
- //[Function: toString] [Function: valueOf]
- let {toString,valueOf}=true;
- console.log(toString,valueOf);
-
- //[Function: toString] [Function: valueOf]