解構(gòu)
ES6 新增了解構(gòu)( destructuring ),它按照一定模式,從數(shù)組和對(duì)象中提取值,對(duì)變量進(jìn)行賦值,這是將一個(gè)數(shù)據(jù)結(jié)構(gòu)分解為更小的部分的過(guò)程。
對(duì)象解構(gòu)
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
默認(rèn)值
當(dāng)你使用解構(gòu)賦值語(yǔ)句時(shí),如果所指定的本地變量在對(duì)象中沒(méi)有找到同名屬性,那么該變量會(huì)被賦值為 undefined 。
let node = {
type: "Identifier",
name: "foo"
};
let { type, name, value } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // undefined
你可以選擇性地定義一個(gè)默認(rèn)值,以便在指定屬性不存在時(shí)使用該值。若要這么做,需要在屬性名后面添加一個(gè)等號(hào)并指定默認(rèn)值。
let node = {
type: "Identifier",
name: "foo"
};
let { type, name, value = true } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // true
賦值給不同的本地變量名
let node = {
type: "Identifier",
name: "foo"
};
let { type: localType, name: localName } = node;
console.log(localType); // "Identifier"
console.log(localName); // "foo"
type: localType 這種語(yǔ)法表示要讀取名為 type 的屬性,并把它的 值存儲(chǔ)在變量 localType 上。該語(yǔ)法實(shí)際上與傳統(tǒng)對(duì)象字面量語(yǔ)法相反,傳統(tǒng)語(yǔ)法將名稱(chēng)放在冒號(hào)左邊、值放在冒號(hào)右邊;而在本例中,則是名稱(chēng)在右邊,需要進(jìn)行值讀取的位置則被放在了左邊。
數(shù)組解構(gòu)
數(shù)組解構(gòu)的語(yǔ)法看起來(lái)與對(duì)象解構(gòu)非常相似,只是將對(duì)象字面量替換成了數(shù)組字面量。數(shù)組解構(gòu)時(shí),解構(gòu)作用在數(shù)組內(nèi)部的位置上,而不是作用在對(duì)象的具名屬性上。
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
只要等號(hào)兩邊的模式相同,左邊的變量就會(huì)被賦予對(duì)應(yīng)的值
剩余項(xiàng)
使用 ... 語(yǔ)法來(lái)將剩余的項(xiàng)目賦值給一個(gè)指定的變量
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
let colors = ["red", "green", "blue"];
let [...clonedColors] = colors;
clonedColors // ["red", "green", "blue"]
剩余項(xiàng)必須是數(shù)組解構(gòu)模式中最后的部分,之后不能再有逗號(hào),否則就是語(yǔ)法錯(cuò)誤。
混合解構(gòu)
對(duì)象與數(shù)組解構(gòu)能被用在一起,以創(chuàng)建更復(fù)雜的解構(gòu)表達(dá)式。在對(duì)象與數(shù)組混合而成的結(jié)構(gòu)中,這么做便能準(zhǔn)確提取其中你想要的信息片段。
let node = {
type: "Identifier",
name: "foo",
loc: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 4
}
},
range: [0, 3]
};
let {
loc: { start },
range: [ startIndex ]
} = node;
console.log(start.line); // 1
console.log(start.column); // 1
console.log(startIndex); // 0
字符串解構(gòu)
字符串也可以解構(gòu)賦值。這是因?yàn)榇藭r(shí),字符串被轉(zhuǎn)換成了一個(gè)類(lèi)似數(shù)組的對(duì)象。
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
類(lèi)似數(shù)組的對(duì)象都有一個(gè)length屬性,因此還可以對(duì)這個(gè)屬性解構(gòu)賦值。
let {length : len} = 'hello';
len // 5
參數(shù)解構(gòu)
當(dāng) JS 的函數(shù)接收大量可選參數(shù)時(shí),一 個(gè)常用模式是創(chuàng)建一個(gè) options 對(duì)象,其中包含了附加的參數(shù)。
// options 上的屬性表示附加參數(shù)
function setCookie(name, value, options) {
options = options || {};
let secure = options.secure,
path = options.path,
domain = options.domain,
expires = options.expires;
// 設(shè)置 cookie 的代碼
}
// 第三個(gè)參數(shù)映射到 options
setCookie("type", "js", {
secure: true,
expires: 60000
});
很多 JS 的庫(kù)都包含了類(lèi)似于此例的 setCookie() 函數(shù)。在此函數(shù)內(nèi), name 與 value 參 數(shù)是必需的,而 secure 、 path 、 domain 與 expires 則不是。此處雖然無(wú)須列出一堆額外的具名參數(shù)。但無(wú)法僅通過(guò)查看函數(shù)定義就判斷出函數(shù)所期望的輸入。參數(shù)解構(gòu)能夠更清楚地標(biāo)明函數(shù)期望輸入。它使用對(duì)象或數(shù)組解構(gòu)的模式替代了具名參數(shù)。
function setCookie(name, value, { secure, path, domain, expires }) { // 設(shè)置 cookie 的代碼
}
setCookie("type", "js", {
secure: true,
expires: 60000
});
解構(gòu)參數(shù)在沒(méi)有傳遞值的情況下類(lèi)似于常規(guī)參數(shù),它們會(huì)被設(shè)為 undefined 。同樣參數(shù)解構(gòu)也可以設(shè)置默認(rèn)值。
用途
互換兩個(gè)變量的值
let a = 1, b = 2;
[a, b] = [b, a ];
console.log(a); // 2
console.log(b); // 1
簡(jiǎn)潔,易讀,語(yǔ)義清晰。
從函數(shù)返回多個(gè)值
// 返回一個(gè)數(shù)組
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一個(gè)對(duì)象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
如果函數(shù)要返回多個(gè)值,我們只能將它們放在數(shù)組或?qū)ο罄锓祷?。有了解?gòu)賦值,取出這些值就非常方便。
提取 JSON 數(shù)據(jù)
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
函數(shù)參數(shù)的定義
// 參數(shù)是一組有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 參數(shù)是一組無(wú)次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
解構(gòu)賦值可以方便地將一組參數(shù)與變量名對(duì)應(yīng)起來(lái)。