ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
一.字符串的解构赋值
1.写法
-
字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象
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.写法
-
解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true
-
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。
let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError
三.函数参数的解构赋值
1.写法
-
函数的参数也可以使用解构赋值。
//一 function add([x, y]){ return x + y; } add([1, 2]); // 3 //二 [[1, 2], [3, 4]].map(([a, b]) => a + b);
-
函数参数的解构也可以使用默认值
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] //不要使用如下写法,方法参数会先解析,在方法调用出现undefined function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, undefined] move({}); // [undefined, undefined] move(); // [0, 0]