《ECMAScript6入門》-變量的解構賦值

1、數組的結構賦值

1.1
let [a, b, c] = [1, 2, 3];

1.2、不完全解構,即等號左邊的模式,只匹配一部分的等號右邊的數組,解構依然可以成功

let [x, y] = [1, 2, 3];
x // 1
y // 2

1.3 如果等號的右邊不是數組,或者不是可遍歷的結構,

// 報錯
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

1.3、解構賦值允許指定默認值

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,默認值纔會生效

2、對象的解構賦值

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

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

解構賦值的規則是,只要等號右邊的值不是對象或數組,就先將其轉爲對象。由於undefined和null無法轉爲對象,所以對它們進行解構賦值,都會報錯。
5、函數參數
6、解構賦值的用途
(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)函數參數的定義
解構賦值可以方便地將一組參數與變量名對應起來。

// 參數是一組有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 參數是一組無次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

(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)函數參數的默認值

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 接口,配合變量的解構賦值,獲取鍵名和鍵值就非常方便。

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

(7)輸入模塊的指定方法
加載模塊時,往往需要指定輸入哪些方法。解構賦值使得輸入語句非常清晰。

const { SourceMapConsumer, SourceNode } = require("source-map");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章