数组的解构赋值
- ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构。
- 本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [x, , y] = [1, 2, 3];
x // 1
y // 3
- 如果解构不成功,变量的值就等于undefined。
let [foo] = [];
let [bar, foo] = [1];
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
- 解构赋值允许指定默认值。但如果一个数组成员不严格等于undefined,默认值是不会生效的。
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
对象的解构赋值
- 对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo
bar
let { baz } = { foo: "aaa", bar: "bbb" };
baz
var { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f
l
- 对象的解构也可以指定默认值。默认值生效的条件是,对象的属性值严格等于undefined。
var {x = 3} = {x: undefined};
x
var {x = 3} = {x: null};
x
let {foo} = {bar: 'baz'};
foo
字符串的解构赋值
- 字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。
const [a, b, c, d, e] = 'hello';
a
b
c
d
e
let {length : len} = 'hello';
len
数值和布尔值的解构赋值
- 解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototype.toString
let {toString: s} = true;
s === Boolean.prototype.toString
函数参数的解构赋值
function add([x, y]){
return x + y;
}
add([1, 2]);
变量的解构赋值用途
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});
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]