数组解构
let [foo, [[bar], baz]] = [1, [[2], 3]];foo // 1bar // 2baz // 3let [ , , third] = ["foo", "bar", "baz"];third // "baz"let [x, , y] = [1, 2, 3];x // 1y // 3let [head, ...tail] = [1, 2, 3, 4];head // 1tail // [2, 3, 4]let [x, y, ...z] = ['a'];x // "a"y // undefinedz // []
对象解构
// 例一let { bar, foo } = { foo: 'aaa', bar: 'bbb' };foo // "aaa"bar // "bbb"// 例二let { log, sin, cos } = Math;
值类型的解构
- 字符串解构赋值
- 字符串被转换成了一个类似数组的对象 ```javascript // 案例一 const [a, b, c, d, e] = ‘hello’; a // “h” b // “e” c // “l” d // “l” e // “o”
// 案例二 let {length : len} = ‘hello’; len // 5
- 数值和布尔值的解构赋值- 数值和布尔值,则会先转为对象```javascriptlet {toString: s} = 123;// new Number()的实例对象中,有toString方法,将它赋给ss === Number.prototype.toString // truelet {toString: s} = true;s === Boolean.prototype.toString // true
