数组解构赋值是一种从数组中提取值的简洁方式。它的语法类似于数组字面量表达式,但位于赋值语句的左侧而不是右侧。
const frenchNumbers = ['quatre-vingts', 'quatre-vingt-dix', 'cent'];
const [french80, french90, french100] = frenchNumbers;
french80;
// => 'quatre-vingts'
french90;
// => 'quatre-vingt-dix'
french100;
// => 'cent'
由于变量按位置映射到数组中的值,解构语法可以用于在单个表达式中为多个变量赋值或重新赋值。
let [a, b] = ['world', 'hello'];
[b, a] = [a, b];
a;
// => 'hello'
b;
// => 'world'
嵌套数组也适用。
let [a, b, c] = ['orange', 'purple', 'green'];
[[a, b], c] = [[c, a], b];
a;
// => 'green'
b;
// => 'orange'
c;
// => 'purple'
该语法允许在映射时跳过值,例如忽略数组中的特定位置。
在下面的示例中,假设有一个getUserInfo函数,它返回一个包含用户名字、姓氏和街道地址的数组。
getUserInfo();
// => ["Valerie", "Noir", "Sunny Lane 523"]
const [, , streetAddress] = getUserInfo();
streetAddress;
// => "Sunny Lane 523"
赋值也不需要使用所有值。
const [firstName, lastName] = getUserInfo();
firstName;
// => "Valerie"
lastName;
// => "Noir"
甚至可以提取比数组包含的_更多_值;剩余的变量将被赋值为undefined。当值的数量事先未知时,这可能很有用。
const pickAtLeastOne = ['first choice', 'second choice'];
const [first, second, third, fourth] = pickAtLeastOne;
first;
// => "first choice"
second;
// => "second choice"
third;
// => undefined
fourth;
// => undefined
数组解构赋值可以提供_默认值_,以防源数组中没有值。
const [first, second, third = 'none selected', fourth] = pickAtLeastOne;
third;
// => 'none selected'
fourth;
// => undefined