數組的解構賦值
基本用法
ES6 允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構(Destructuring)。
// 為變量賦值,只能直接指定值。
let a = 1;
let b = 2;
let c = 3;
// ES6 允許寫成下面這樣
let [a, b, c] = [1, 2, 3];
// 嵌套數組進行解構的例子
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
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
// 如果解構不成功,foo 的值都會等于 undefined
let [foo] = [];
let [bar, foo] = [1];
// 不完全解構,但是可以成功
let [x, y] = [1, 2, 3];
x // 1
y // 2
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
// 等號的右邊不是數組,報錯
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
// Set 結構,也可以使用數組的解構賦值
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
// 事實上,只要某種數據結構具有 Iterator 接口,都可以采用數組形式的解構賦值。
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
默認值
// 解構賦值允許指定默認值
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
注意,ES6 內部使用嚴格相等運算符(===),判斷一個位置是否有值。所以,如果一個數組成員不嚴格等于undefined,默認值是不會生效的。
// 如果一個數組成員是null,默認值就不會生效,因為null不嚴格等于undefined
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
// 如果默認值是一個表達式,那么這個表達式是惰性求值的,即只有在用到的時候,才會求值
function f() {
console.log('aaa');
}
let [x = f()] = [1];
//上面代碼中,因為x能取到值,所以函數f根本不會執行。上面的代碼其實等價于下面的代碼。
// 默認值可以引用解構賦值的其他變量,但該變量必須已經聲明
let x;
if ([1][0] === undefined) {
x = f();
} else {
x = [1][0];
}
// 表達式之所以會報錯,是因為x用到默認值y時,y還沒有聲明
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError
對象的解構賦值
解構不僅可以用于數組,還可以用于對象
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
// 對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值
let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined
// 如果變量名與屬性名不一致,必須寫成下面這樣
var { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'
// 對象的解構賦值的內部機制,是先找到同名屬性,然后再賦給對應的變量。真正被賦值的是后者,而不是前者
let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };
// foo是匹配的模式,baz才是變量。真正被賦值的是變量baz,而不是模式foo
let { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined
// 對于let和const來說,變量不能重新聲明
let foo;
let {foo} = {foo: 1}; // SyntaxError: Duplicate declaration "foo"
let baz;
let {bar: baz} = {bar: 1}; // SyntaxError: Duplicate declaration "baz"
// let命令下面一行的圓括號是必須的,否則會報錯
let foo;
({foo} = {foo: 1}); // 成功
let baz;
({bar: baz} = {bar: 1}); // 成功
解構也可以用于嵌套結構的對象
// 這時p是模式,不是變量,因此不會被賦值
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
// 只有line是變量,loc和start都是模式,不會被賦值
var node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
var { loc: { start: { line }} } = node;
line // 1
loc // error: loc is undefined
start // error: start is undefined
// 嵌套賦值的例子
let obj = {};
let arr = [];
({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });
obj // {prop:123}
arr // [true]
對象的解構也可以指定默認值
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
var {x:y = 3} = {};
y // 3
var {x:y = 3} = {x: 5};
y // 5
var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
// 生效的條件是,對象的屬性值嚴格等于undefined
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null
// 如果解構失敗,變量的值等于undefined
let {foo} = {bar: 'baz'};
foo // undefined
// 因為foo這時等于undefined,再取子屬性就會報錯
let {foo: {bar}} = {baz: 'baz'};
// 等價
let _tmp = {baz: 'baz'};
_tmp.foo.bar // 報錯
// 錯誤的寫法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
// 正確的寫法
let x;
({x} = {x: 1});
// 解構賦值允許,等號左邊的模式之中,不放置任何變量名
// 表達式雖然毫無意義,但是語法是合法的
({} = [true, false]);
({} = 'abc');
({} = []);
- 將現有對象的方法,賦值到某個變量
let { log, sin, cos } = Math;
- 數組本質是特殊的對象,因此可以對數組進行對象屬性的解構
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
字符串的解構賦值
字符串也可以解構賦值。這是因為此時,字符串被轉換成了一個類似數組的對象
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
- 類似數組的對象都有一個length屬性,因此還可以對這個屬性解構賦值
let {length : len} = 'hello';
len // 5
數值和布爾值的解構賦值
解構賦值時,如果等號右邊是數值和布爾值,則會先轉為對象
// 數值和布爾值的包裝對象都有toString屬性,因此變量s都能取到值
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
// 由于undefined和null無法轉為對象,所以對它們進行解構賦值,都會報錯
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
函數參數的解構賦值
// 函數add的參數表面上是一個數組,但在傳入參數的那一刻,數組參數就被解構成變量x和y。對于函數內部的代碼來說,它們能感受到的參數就是x和y
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
// demo
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]
函數參數的解構也可以使用默認值
// 函數move的參數是一個對象,通過對這個對象進行解構,得到變量x和y的值。如果解構失敗,x和y等于默認值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
// 注意,下面的寫法會得到不一樣的結果
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
undefined就會觸發函數參數的默認值
[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]
圓括號問題
解構賦值雖然很方便,但是解析起來并不容易。對于編譯器來說,一個式子到底是模式,還是表達式,沒有辦法從一開始就知道,必須解析到(或解析不到)等號才能知道。
由此帶來的問題是,如果模式中出現圓括號怎么處理。ES6的規則是,只要有可能導致解構的歧義,就不得使用圓括號。
但是,這條規則實際上不那么容易辨別,處理起來相當麻煩。因此,建議只要有可能,就不要在模式中放置圓括號。
不能使用圓括號的情況
- 變量聲明語句中,不能帶有圓括號
// 全部報錯
let [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2 } };
- 函數參數中,模式不能帶有圓括號
// 函數參數也屬于變量聲明,因此不能帶有圓括號
function f([(z)]) { return z; }
- 賦值語句中,不能將整個模式,或嵌套模式中的一層,放在圓括號之中
// 全部報錯
({ p: a }) = { p: 42 };
([a]) = [5];
// 報錯
[({ p: a }), { x: c }] = [{}, {}];
可以使用圓括號的情況
可以使用圓括號的情況只有一種:賦值語句的非模式部分,可以使用圓括號。
[(b)] = [3]; // 正確
({ p: (d) } = {}); // 正確
[(parseInt.prop)] = [3]; // 正確
因為首先它們都是賦值語句,而不是聲明語句;其次它們的圓括號都不屬于模式的一部分。第一行語句中,模式是取數組的第一個成員,跟圓括號無關;第二行語句中,模式是p,而不是d;第三行語句與第一行語句的性質一致
用途
- 交換變量值
let x = 1;
let y = 2;
[x, y] = [y, x];
- 從函數返回多個值
函數只能返回一個值,如果要返回多個值,只能將它們放在數組或對象里返回。有了解構賦值,取出這些值就非常方便
// 返回一個數組
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一個對象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
- 函數參數的定義
// 解構賦值可以方便地將一組參數與變量名對應起來。
// 參數是一組有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 參數是一組無次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
- 提取 JSON 數據
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
- 函數參數的默認值
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
}) {
// ... do stuff
};
- 遍歷 Map 結構
任何部署了Iterator接口的對象,都可以用for...of循環遍歷。Map結構原生支持Iterator接口,配合變量的解構賦值,獲取鍵名和鍵值就非常方便
var 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) {
// ...
}
- 輸入模塊的指定方法
// 加載模塊時,往往需要指定輸入哪些方法。解構賦值使得輸入語句非常清晰
const { SourceMapConsumer, SourceNode } = require("source-map");