变量的解构赋值
一.数组的解构赋值
let [a,b,c] = [1,2,3]; console.log(a);//1 console.log(b);//2 console.log(c);//3
let [head,...tail] = [1,2,3,4,5]; console.log(head);//1 console.log(tail);//[2,3,4,5]
let [x, y, ...z] = ['a']; console.log(x);//a console.log(y);//undefined (如果解构不成功,变量的值为undefined) console.log(z);//[]
let [x,y,z] = new Set([1,2,3]); console.log(x);//1 console.log(y);//2 console.log(z);//3
(只要某种数据结构具有Iterator接口,就可以采用数组形式的解构赋值)
Iterator:遍历器( Iterator) 就是这样一种机制。 它是一种接口, 为各种不同的数据结构提供统一的访问机制。 任何数据结构只要部署 Iterator 接口, 就可以完成遍历操作( 即依次处理该数据结构的所有成员)。
二。对象的解构赋值
对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。
let { foo: baz } = { foo: "aaa", bar: "bbb" }; baz // "aaa" foo // error: foo is not defined
对象的解构也可以指定默认值。
如果要将一个已经声明的变量用于解构赋值,必须非常小心
// 错误的写法 let x; {x} = {x: 1}; // SyntaxError: syntax error
三。字符串的解构赋值
字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。
const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o"
类似数组的对象都有一个length
属性,因此还可以对这个属性解构赋值。
let {length : len} = 'hello'; len // 5
四。函数参数的解构赋值
[[1, 2], [3, 4]].map(([a, b]) => a + b); // [ 3, 7 ]
函数参数的解构也可以使用默认值。
function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); // [0, 0]