ES6 —— 變量的解構賦值

ES6 允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱爲解構。

1. 數組的解構賦值

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 // []

上面的代碼表示,可以從數組中提取值,按照對應位置,爲變量賦值。
本質上,這種寫法屬於“模式匹配”,只要等號兩邊的模式相同,左邊的變量就會被賦予對應的值。

如果解構不成功,變量的值就會爲 undefined。

解構允許指定默認值。當一個數組成員嚴格等於 undefined 時,默認值纔會生效。

let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

2. 對象的解構賦值

對象的解構與數組有一個重要的不同。數組的元素是按次序排列的,變量的取值由它的位置決定;而對象的屬性沒有次序,所以變量必須與屬性相同,才能取到對應的值。

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined

如果變量名和屬性名不一致,必須寫成下面這樣:

let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'

上面的代碼中,first 、last 只是匹配的模式,f、l 纔是被賦值的變量。

嵌套對象的解構:

let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};
let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p // ["Hello", {y: "World"}]

對象的解構也可以設置默認值,默認值生效的條件是對象的屬性值嚴格等於 undefined。

3. 字符串的解構賦值

字符串也可以進行解構賦值,因爲此時字符串被轉化成了一種類似數組的對象。
類似數組的對象都有一個 length 屬性,因此還可以對這個屬性進行解構賦值。

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

let {length: len} = 'hello';
len //5

4. 數值和布爾值的解構賦值

解構賦值的規則是,只要等號右邊的值不是對象或數組,就先將其轉爲對象。由於undefined和null無法轉爲對象,所以對它們進行解構賦值,都會報錯。

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError

上面代碼中,數值和布爾值的包裝對象都有toString屬性,因此變量s都能取到值。

5. 函數參數的解構賦值

[[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]

6. 用途

  • 交換變量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
  • 從函數返回多個值
// 返回一個數組
function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();
  • 函數參數的定義

解構賦值可以方便的將一組參數與變量名對應起來

function f([x, y, z]) { ... }
f([1, 2, 3]);
  • 提取 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]
  • 函數參數的默認值
jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};
  • 遍歷 map 結構
// 獲取鍵名
for (let [key] of map) {
  // ...
}
for (let [key, value] of map) {//獲取鍵名和鍵值
  console.log(key + " is " + value);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章