ES6中的解构赋值,用来从数组或对象中提取数据。
例如:
[a, b] = [1, 2]
[a, b, ...rest] = [1, 2, 3, 4, 5]
{a, b} = {a:1, b:2}
{a, b, ...rest} = {a:1, b:2, c:3, d:4} //ES7,暂不支持
注:
(1)[a, b]=[1, 2]
相当于var [a, b]=[1, 2]
(2)“{a, b} = {a:1, b:2}
”单独写是不合法的,因为{a, b}
会被解析成一个语句块。
所以应该写为“({a, b} = {a:1, b:2})
”,或者“var {a, b} = {a:1, b:2}
”
(3)解构是支持嵌套的,如果模式匹配不成功,会报语法错误。
Static Semantics: Early Errors
DestructuringAssignmentTarget : LeftHandSideExpression
It is a Syntax Error if
LeftHandSideExpression
is either anObjectLiteral
or anArrayLiteral
and if the lexical token sequence matched byLeftHandSideExpression
cannot be parsed with no tokens left over usingAssignmentPattern
as the goal symbol.
用法:
(1)数组解构
var foo = ["one", "two", "three"];
var [one, two, three] = foo;
(2)交换赋值
[a, b]=[b, a]
(3)返回多值
var [a, b]=f();
function f(){
return [1, 2];
}
(4)忽略部分值
var [a, , b] = f(); //接受第一个和第三个值
(5)用于正则表达式
var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
//返回一个数组,第一个元素是匹配,其余元素是捕获组
var [, protocol, fullhost, fullpath] = parsedURL;
(6)对象解构
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
(7)对象解构重新赋值
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
(8)用字符串匹配键的名字
let key = "z";
let { [key]: foo } = { z: "bar" };
console.log(foo); // "bar"
(9)嵌套解构
var metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localization_tags: [],
last_edit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung'
}
],
url: '/en-US/docs/Tools/Scratchpad'
};
var {title: englishTitle, translations: [{title: localeTitle}]} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
参考
ECMAScript Specification – Destructuring Assignment
MDN – Destructuring assignment