1. 程式人生 > >es6-變數的解構賦值

es6-變數的解構賦值

ES6 允許按照一定模式,從陣列和物件中提取值,對變數進行賦值,這被稱為解構(Destructuring)。

1.陣列的解構賦值

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 如果解構不成功,變數的值就等於undefined。
z // []

如果等號的右邊不是陣列(或者嚴格地說,不是可遍歷的結構,參見《Iterator》一章),那麼將會報錯。

// 報錯
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'

ES6 內部使用嚴格相等運算子(===),判斷一個位置是否有值。所以,只有當一個數組成員嚴格等於undefined,預設值才會生效。

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

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

如果預設值是一個表示式,那麼這個表示式是惰性求值的,即只有在用到的時候,才會求值。

function f() {
  console.log('aaa');
}

let [x = f()] = [1];//1
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: y is not defined

2.物件的解構賦值

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

物件的解構與陣列有一個重要的不同。陣列的元素是按次序排列的,變數的取值由它的位置決定;而物件的屬性沒有次序,變數必須與屬性同名,才能取到正確的值。
如果變數名與屬性名不一致,必須寫成下面這樣。

let { 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" };

物件的解構賦值的內部機制,是先找到同名屬性,然後再賦給對應的變數。真正被賦值的是後者,而不是前者。

let { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined

上面程式碼中,foo是匹配的模式,baz才是變數。真正被賦值的是變數baz,而不是模式foo。

與陣列解構相同的是,物件也可以指定預設值,規則和陣列一樣,物件的屬性值必須嚴格等於undefined,預設值才能生效。

3.字串解構賦值

字串會被轉換為一個數組物件,類似陣列的物件都有一個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.用途

(1)變數交換值

let x = 1;
let y = 2;

[x, y] = [y, x];

(2)從函式返回多個值
函式只能返回一個值,如果要返回多個值,就要放在陣列或者物件裡面返回。

// 返回一個數組

function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回一個物件

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

(3)函式引數定義
(4)提取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]

(5)遍歷Map結構
任何部署了 Iterator 介面的物件,都可以用for…of迴圈遍歷。Map 結構原生支援 Iterator 介面,配合變數的解構賦值,獲取鍵名和鍵值就非常方便。

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) {
  // ...
}