目錄
1.數組的解構賦值
解構
:ES6允許按照一定模式,從數組和對象中提取值,對變量進行賦值。
傳統寫法:
var a = 1;
var b = 2;
var c = 3;
ES6:
var [a, b, c] = [1, 2, 3];
數組解構實例:
let [foo, [[bar],baz]] = [1,[[2],3]];
foo // 1
bar // 2
baz // 3
let [ , ,third] = ['foo','bar','bar'];
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 // []
解構失敗:
let [foo] = []; // foo == undefined
let [bar, foo] = [1]; //bar == 1, foo == undefined
不完全解構:
let [x, y] = [1, 2, 3];
x // 1
y // 2
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
解構式兩邊都應該是數組:
// error
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
解構賦值允許指定默認值:
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
數組成員嚴格等於undefined是才使用默認值.
默認值可以引用解構賦值的其他變量,但該變量必須已經聲明。
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
2.對象的解構賦值
對象解構:
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'
foo
是匹配的模式,baz
纔是變量。真正被賦值的是變量baz
,而不是模式foo
。
let { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined
對象的解構也可以指定默認值。
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"
對象的解構賦值,可以很方便地將現有對象的方法,賦值到某個變量(*這個會經常用到的
):
let { log, sin, cos } = Math;
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
4.數值和布爾值的解構賦值
解構賦值時,如果等號右邊是數值和布爾值,則會先轉爲對象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
上面代碼中,數值和布爾值的包裝對象都有toString
屬性,因此變量s
都能取到值。
解構賦值的規則是,只要等號右邊的值不是對象或數組,就先將其轉爲對象。由於undefined
和null
無法轉爲對象,所以對它們進行解構賦值,都會報錯。
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
5.函數參數的解構賦值
函數參數解構:
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
函數add
的參數表面上是一個數組,但在傳入參數的那一刻,數組參數就被解構成變量x
和y
。對於函數內部的代碼來說,它們能感受到的參數就是x
和y
。
下面是另一個例子。
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]
函數參數的解構也可以使用默認值。
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]
上面代碼中,函數move
的參數是一個對象,通過對這個對象進行解構,得到變量x
和y
的值。如果解構失敗,x
和y
等於默認值。
注意,下面的寫法會得到不一樣的結果。
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]
上面代碼是爲函數move
的參數指定默認值,而不是爲變量x
和y
指定默認值,所以會得到與前一種寫法不同的結果。
undefined
就會觸發函數參數的默認值。
[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]
6.用途總結
變量的解構賦值很方便實用。
(1)交換變量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
上面代碼交換變量x
和y
的值,這樣的寫法不僅簡潔,而且易讀,語義非常清晰。
(2)從函數返回多個值
函數只能返回一個值,如果要返回多個值,只能將它們放在數組或對象裏返回。有了解構賦值,取出這些值就非常方便。
// 返回一個數組
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一個對象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
(3)函數參數的定義
解構賦值可以方便地將一組參數與變量名對應起來。
// 參數是一組有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 參數是一組無次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
(4)提取JSON數據
解構賦值對提取JSON對象中的數據,尤其有用。
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
上面代碼可以快速提取 JSON 數據的值。
(5)函數參數的默認值
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
}) {
// ... do stuff
};
指定參數的默認值,就避免了在函數體內部再寫var foo = config.foo || 'default foo';
這樣的語句。
(6)遍歷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) {
// ...
}
(7)輸入模塊的指定方法
加載模塊時,往往需要指定輸入哪些方法。解構賦值使得輸入語句非常清晰。
const { SourceMapConsumer, SourceNode } = require("source-map");