發(fā)布于:2021-02-06 00:00:30
0
99
0
解構(gòu)已成為JavaScript的主要語(yǔ)言功能,其中最明顯的體現(xiàn)是導(dǎo)入,還包括函數(shù)聲明 等。雖然對(duì)象文字是解構(gòu)的通常情況,但請(qǐng)記住,您也可以解構(gòu)數(shù)組和集合。讓我們看看如何對(duì)數(shù)組和集合使用解構(gòu)!解構(gòu)的通常情況是使用對(duì)象文字:
const dict = { prop1: "one", prop2: "two" };
const { prop1, prop2 } = dict;
// prop1 = "one"
// prop2 = "two"
數(shù)組和集合解構(gòu)的語(yǔ)法有些不同:
const arr = ["uno", "dos"];
const [one, two] = arr;
// one = "uno"
// two = "dos"
// Or more explicitly
const [width, height] = [200, 400];
迭代中的解構(gòu)語(yǔ)法如下:
const items = [
["one", "two"],
["three", "four"]
];
items.forEach(([uno, dos]) => {
console.log(uno, dos);
});
// "one", "two"
// "three", "foor"
您還可以通過(guò)解構(gòu)來(lái)克隆數(shù)組:
const arr = ["one", "two"];
const clone = [...arr];
如果您不關(guān)心數(shù)組的給定索引,也可以使用逗號(hào)來(lái)占優(yōu)勢(shì):
const arr = [1, 2, 3, 4];
const [,,,four] = arr; // four === 4
對(duì)于熟練的JavaScript開(kāi)發(fā)人員而言,解構(gòu)非常棒,并且可能使新手感到困惑。基本的數(shù)組解構(gòu)不會(huì)誤導(dǎo)太多,但是迭代可能是一個(gè)丑陋的片段?;ㄒ稽c(diǎn)時(shí)間看一下這些簡(jiǎn)化的示例,可能會(huì)幫助您更好地理解這種模式。
作者介紹
熱門博客推薦