一、字符串的解構(gòu)賦值
//字符串也能解構(gòu)賦值,因此時字符串被轉(zhuǎn)換成了一個類似數(shù)組的對象(類似于字符串的split方法)
let str = 'abcdefg';
let arr = str.split('');
console.log(arr); // [a, b, c, d, e, f, g]
const [a, b, c, d, e] = 'hello';
console.log(a, b, c, d, e); // h, e, l, l, o
// 類似數(shù)組的對象都有一個length屬性,因此還可以對這個屬性進行解構(gòu)賦值
let { length: len } = 'hello';
console.log(len); // 5
二、數(shù)值和布爾值的解構(gòu)賦值
// 解構(gòu)賦值時,如果等號右邊是數(shù)值和布爾值,則會先轉(zhuǎn)為對象,通過對象的原型進行解構(gòu)
// 以下代碼中,因為數(shù)值和布爾值的包裝對象都有toString屬性,因此s、m都能取到值
let { toString: s } = 123;
console.log(s);
console.log(s === Number.prototype.toString); // true
let { toString: m } = true;
console.log(m);
console.log(m === Boolean.prototype.toString); // true
// 解構(gòu)賦值的規(guī)則是,只要等號右邊的值不是對象或數(shù)組,就先將其轉(zhuǎn)為對象
// 由于undefined和null無法轉(zhuǎn)為對象,所以對它們進行解構(gòu)賦值時都會報錯
let { prop: x } = undefined; // 報錯:TypeError
let { prop: y } = null; // 報錯:TypeError
三、用途、
1. 交換變量的值
let x = 1;
let y = 2;
[x, y] = [y, x]; //簡潔,易讀,語義非常清晰
2. 從函數(shù)返回多個值
/*函數(shù)只能返回一個值,如要返回多個值,只能將它們放在數(shù)組或?qū)ο罄锓祷亍?利用解構(gòu)賦值,取出這些值就非常方便。*/
// 返回一個數(shù)組
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一個對象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
3. 函數(shù)參數(shù)的定義
解構(gòu)賦值可以方便地將一組參數(shù)與變量名對應起來。
// 參數(shù)是一組有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 參數(shù)是一組無次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
4. 提取 JSON 數(shù)據(jù)
解構(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]
5. 函數(shù)參數(shù)的默認值
指定參數(shù)的默認值,就避免了在函數(shù)體內(nèi)部再寫var foo = config.foo || 'default foo';這樣的語句。
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};
6. 遍歷 Map 結(jié)構(gòu)
任何部署了 Iterator 接口的對象,都可以用for...of循環(huán)遍歷。Map 結(jié)構(gòu)原生支持 Iterator 接口,配合變量的解構(gòu)賦值,獲取鍵名和鍵值就非常方便。
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
如果只想獲取鍵名,或者只想獲取鍵值,可以寫成下面這樣。
// 獲取鍵名
for (let [key] of map) {
// ...
}
// 獲取鍵值
for (let [,value] of map) {
// ...
}
7. 輸入模塊的指定方法
加載模塊時,往往需要指定輸入哪些方法。解構(gòu)賦值使得輸入語句非常清晰。
const { SourceMapConsumer, SourceNode } = require("source-map");
8.對于 Set 結(jié)構(gòu)/Generator 函數(shù),使用數(shù)組的解構(gòu)賦值。
事實上,只要某種數(shù)據(jù)結(jié)構(gòu)具有 Iterator 接口,都可以采用數(shù)組形式的解構(gòu)賦值。
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
//fibs是一個 Generator 函數(shù),原生具有 Iterator 接口。解構(gòu)賦值會依次從這個接口獲取值。
function* fibs() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5