很多内容还需要琢磨,尤其是对象和函数参数的解构赋值
1.解构(Destructuring):ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,
let [foo, [[bar], baz]] = [1, [[2], 3]]; foo // 1 bar // 2 baz // 3 let [ , , third] = ["foo", "bar", "baz"]; third // "baz" let [x, , y] = [1, 2, 3]; x // 1 y // 3 let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4] let [x, y, ...z] = ['a']; x // "a" y // undefined z // []
不完全结构依然可以解构成功
let [x, y] = [1, 2, 3]; x // 1 y // 2 let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4
解构不成功 报undefined
2.对象的解构赋值
对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
let { foo, bar } = { foo: 'aaa', bar: 'bbb' }; foo // "aaa" bar // "bbb" let { bar, foo } = { foo: 'aaa', bar: 'bbb' }; foo // "aaa" bar // "bbb" let { baz } = { foo: 'aaa', bar: 'bbb' }; baz // undefined
变量名与属性名不一致,必须写成下面这样
let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa" let obj = { first: 'hello', last: 'world' }; let { first: f, last: l } = obj; f // 'hello' l // 'world'
对象的解构赋值的内部机制是先找到同名属性,然后再赋给对应的变量。真正被赋值的是变量,而不是属性。如:
let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa" foo // error: foo is not defined
const node = { loc: { start: { line: 1, column: 5 } } }; let { loc, loc: { start }, loc: { start: { line }} } = node; line // 1 line是变量 start loc是模式不赋值 loc // Object {start: Object} start // Object {line: 1, column: 5}
对象的解构赋值可以取到继承的属性
const obj1 = {}; const obj2 = { foo: 'bar' }; Object.setPrototypeOf(obj1, obj2); const { foo } = obj1; foo // "bar"
这里的setPrototypeOf是将一个指定对象的原型设置为另一个对象或者null既对象的prototype内部属性). Object.setPrototypeOf(obj, prototype)
注意对于一个已经声明的变量用于解构赋值,必须要注意直接这样会报错
let x; {x} = {x: 1}; // {x}变成了一个代码块 let x; ({x} = {x: 1}); //正确 // 尽量不要在模式中放置圆括号(),因为编译器对辨别是不是解构不是特别的容易 可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号。
字符串的解构赋值
字符串解构赋值时被转换成一个类似数组的对象
const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o" let {length : len} = 'hello'; len // 5
数值和布尔值的解构赋值
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined
和null
无法转为对象,所以对它们进行解构赋值,都会报错。
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError
用途
交换变量的值
let x = 1; let y = 2; [x, y] = [y, x];
从函数返回多个值
// 返回一个数组 function example() { return [1, 2, 3]; } let [a, b, c] = example(); // 返回一个对象 function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example();
函数参数的定义
很方便的将一组函数与变量名对应起来。
// 参数是一组有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]); // 参数是一组无次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});