ES6之解構賦值

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

誰可以解構

  數組可以用數組解構,對於 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

  上面代碼中,fibs是一個 Generator 函數(參見Generator 函數),原生具有 Iterator 接口。解構賦值會依次從這個接口獲取值。
  上面的語句都會報錯,因爲等號右邊的值,要麼轉爲對象以後不具備 Iterator 接口(前五個表達式),要麼本身就不具備 Iterator 接口(最後一個表達式)。
  當解構賦值表達式的右側(=後面的表達式)的計算結果爲null或undefined時,會拋出錯誤。因爲任何讀取null或undefined的企圖都會導致“運行時”錯誤(runtime error)。

解構缺少初始化報錯

  當使用解構來配合var 、let或const來聲明變量時,必須提供初始化器(即等號右邊的值)。下面的代碼都會因爲缺失初始化器而拋出錯誤:

//    語法錯誤!
var    {type,name};
//    語法錯誤!
let    {type,name};
//    語法錯誤!
const {type,name};

  與對象解構相似,在使用var 、let 、const 進行數組解構時,你必須提供初始化器。

已聲明變量用於解構賦值

對象

// 錯誤的寫法
let x;
{x} = {x: 1};
// SyntaxError: syntax error

  上面代碼的寫法會報錯,因爲 JavaScript 引擎會將{x}理解成一個代碼塊,從而發生語法錯誤。只有不將大括號寫在行首,避免 JavaScript 將其解釋爲代碼塊,才能解決這個問題。

// 正確的寫法
let x;
({x} = {x: 1});

數組

  你可以在賦值表達式中使用數組解構,但是與對象解構不同,不必將表達式包含在圓括號
內,例如:

let    colors=["red","green","blue"    ],
let    firstColor    =    "black",
let    secondColor    =    "purple";
[firstColor,secondColor    ]    =    colors;
console.log(firstColor);//    "red"
console.log(secondColor);//    "green"

解構賦值表達式的值

  解構賦值表達式的值爲表達式右側(在 = 之後)的值。也就是說在任何期望有個值的位置都可以使用解構賦值表達式。例如,傳遞值給函數:

let    node={type:    "Identifier",name:    "foo"},
let type = "Literal",
let name = 5;
function    outputInfo(value)    {
    console.log(value    ===    node);    //    true
}

outputInfo({type,name}=node);

console.log(type);//    "Identifier"
console.log(name);//    "foo"

數組的解構賦值

數組解構賦值表達式的右值報錯

  如果等號的右邊不是數組(或者嚴格地說,不是可遍歷的結構,參見Iterator),那麼將會報錯。
  如果左邊是用{}來解構,會把右值轉爲對象,除了null和undefined以外都不會報錯。

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

一維數組的解構

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

  上面代碼表示,可以從數組中提取值,按照對應位置,對變量賦值。

嵌套數組的解構

let    [firstColor,[secondColor]] = ["red",["green","lightgreen"],"blue"];
console.log(firstColor);//    "red"
console.log(secondColor);//    "green"

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 [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

let    [,firstColor,[secondColor]] = ["red","blue",["green","lightgreen"]];
firstColor//blue
secondColor//["green","lightgreen"]

解構不成功

  當指定位置的項不存在、或其值爲undefined ,則解構不成功,變量的值就等於undefined。

let [foo] = [];
let [bar, foo] = [1];

默認值

  當指定位置的項解構不成功時,那麼該默認值就會被使用。
  注意,ES6 內部使用嚴格相等運算符(===),判斷一個位置是否有值。所以,只有當一個數組成員嚴格等於undefined,默認值纔會生效。
  如果一個數組成員是null,默認值就不會生效,因爲null不嚴格等於undefined。

let    colors = ["red"];
let    [firstColor,secondColor    = "green"]=colors
console.log(firstColor);//"red"
console.log(secondColor);//    "green"

let [foo = true] = [];
foo // true

  如果默認值是一個表達式,那麼這個表達式是惰性求值的,即只有在用到的時候,纔會求值。

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

let [x = f()] = [1];

  上面代碼中,因爲x能取到值,所以函數f根本不會執行。上面的代碼其實等價於下面的代碼。
  默認值可以引用解構賦值的其他變量,但該變量必須已經聲明。

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

剩餘項解構

  數組解構有個類似的、名爲剩餘項( rest items )的概念,它使用...語法來將剩餘的項目賦值給一個指定的變量。

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

但它還有另一個有用的功能。方便地克隆數組在 JS 中是個明顯被遺漏的功能。在ES5中開發者往往使用的是一個簡單的方式,也就是用concat() 方法來克隆數組。

var    colors = ["red","green","blue"];
var    clonedColors = colors.concat();
console.log(clonedColors);//"[red,green,blue]"

  而在ES6中,你可以使用剩餘項的語法來達到同樣效果。實現如下:

let    colors = ["red","green","blue"];
let    [...clonedColors] = colors;
console.log(clonedColors);//"[red,green,blue]"

  注意!剩餘項必須是數組解構模式中最後的部分,之後不能再有逗號,否則就是語法錯誤。

對象的解構賦值

  解構不僅可以用於數組,還可以用於對象。對象的解構與數組有一個重要的不同。數組的元素是按次序排列的,變量的取值由它的位置決定;而對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。
  對象的解構賦值的解構和數組的差不多,只是[]換爲了{},嵌套對象多了個:,還有對象不在乎屬性的順序,所以對象的不完全解構是不必要像數組那樣的,想要哪個屬性直接寫屬性名就行了,同時還多了個別名的設置。

//普通對象的解構
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

//嵌套對象的解構
let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};
let { p: [x, { y }] } = obj;
//注意,這時p是模式,不是變量,因此不會被賦值。
//如果p也要作爲變量賦值,可以寫成下
//let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
//另一個例子 
const node = {
  loc: {
    start: {
      line: 1,
      column: 5
    }
  }
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // Object {start: Object}
start // Object {line: 1, column: 5}
//注意,最後一次對line屬性的解構賦值之中,只有line是變量,loc和start都是模式,不是變量。

//默認值
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
//默認值生效的條件是,對象的屬性值嚴格等於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 arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
//length屬性
let {length : len} = [1,2,3];
len//3

設置別名

  ES6 有一個擴展語法,允許你在給本地變量賦值時使用一個不同的名稱。

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'

字符串的解構賦值

  字符串也可以解構賦值。這是因爲此時,字符串被轉換成了一個類似數組的對象。

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

  類似數組的對象都有一個length屬性,因此還可以對這個屬性解構賦值。

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

數值和布爾值的解構賦值

  解構賦值時,如果等號右邊是數值和布爾值,則會先轉爲對象。

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

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

let {toString} = NaN;
toString === Number.prototype.toString//true

函數參數的解構賦值

  函數的參數也可以使用解構賦值。

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3

  上面代碼中,函數add的參數表面上是一個數組,但在傳入參數的那一刻,數組參數就被解構成變量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]

  上面代碼中,函數move的參數是一個對象,通過對這個對象進行解構,得到變量x和y的值。如果解構失敗,x和y等於默認值。當 JS 的函數接收大量可選參數時,一個常用模式是創建一個 options 對象,其中包含了附加的參數。

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]

  js會先把實參傳進形參的右值,代替左值,如果沒傳,默認用形參的右值。
  undefined就會觸發函數參數的默認值。

[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]

用途

交換變量的值

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({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);
// 42, "OK", [867, 5309]

函數參數的默認值

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';這樣的語句。

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

輸入模塊的指定方法

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

const { SourceMapConsumer, SourceNode } = require("source-map");

參考文章:
ECMAScript 6 入門

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章