ES6解构赋值的游戏规则

ES6解构赋值的游戏规则:

第一步:先分出数组还是对象,看[]、{}
第二步:
1.数组解构,变量a(顺序),对象...b
2.对象解构

 

数组解构:

 1 let [foo, [[bar], baz]] = [1, [[2], 3]];
 2 foo // 1
 3 bar // 2
 4 baz // 3
 5 
 6 let [ , , third] = ["foo", "bar", "baz"];
 7 third // "baz"
 8 
 9 let [x, , y] = [1, 2, 3];
10 x // 1
11 y // 3
12 
13 let [head, ...tail] = [1, 2, 3, 4];
14 head // 1
15 tail // [2, 3, 4]
16 
17 let [x, y, ...z] = ['a'];
18 x // "a"
19 y // undefined
20 z // []

对象解构:

 1 let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
 2 foo // "aaa"
 3 bar // "bbb"
 4 
 5 let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
 6 baz // "aaa"
 7 
 8 let obj = { first: 'hello', last: 'world' };
 9 let { first: f, last: l } = obj;
10 f // 'hello'
11 l // 'world'

字符串本身就是数组的形式:

1 var [a,b,c,d,e] = 'hello';
2 console.log(a);//h
3 console.log(b);//e

数组可以调用本身的属性;对象也可以调用自带的属性与方法:

 1 var tt=[1,2,3];
 2 var {length,concat}=tt;
 3 console.log(length);//3
 4 console.log(concat);//ƒ concat() { [native code] }
 5 
 6 let {toString: s} = 123;
 7 console.log(s === Number.prototype.toString);
 8 // true
 9 
10 let {toString: s} = true;
11 console.log(s === Boolean.prototype.toString);
12 // true

 

posted @ 2020-09-23 16:52  土生  阅读(168)  评论(0)    收藏  举报