ES6 解構(gòu)

解構(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)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前面的話(huà) 我們經(jīng)常定義許多對(duì)象和數(shù)組,然后有組織地從中提取相關(guān)的信息片段。在ES6中添加了可以簡(jiǎn)化這種任務(wù)的新特性...
    sunnyghx閱讀 825評(píng)論 0 0
  • 參考:ES6入門(mén)(阮一峰)解構(gòu):解構(gòu)與構(gòu)造數(shù)據(jù)截然相反。 例如,它不是構(gòu)造一個(gè)新的對(duì)象或數(shù)組,而是逐個(gè)拆分現(xiàn)有的對(duì)...
    IceLake閱讀 4,114評(píng)論 0 2
  • 注意:iOS所有圖標(biāo)的圓角效果由系統(tǒng)生成,給到的圖標(biāo)本身不能是圓角的。 桌面圖標(biāo) (app icon)for iP...
    獨(dú)居焚香閱讀 545評(píng)論 0 3
  • Mixed martial arts (MMA) is a full-contact combat sport t...
    怪物辦公室閱讀 356評(píng)論 0 0
  • 如果診斷的目的是為了治愈的話(huà)。 如果本身能夠治愈為什么要冠上診斷后的標(biāo)簽久久不能抬頭與治愈。
    朱周閱讀 254評(píng)論 0 0

友情鏈接更多精彩內(nèi)容