ES6——解構賦值

1、數組

let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]; // foo = 1, bar = 2, baz = 3
let [x, y, ...z] = ['a']; // x = 'a', y = undefined, z = []
let [a, [b], d] = [1, [2, 3], 4]; // a = 1, b = 2, d = 4

數組的屬性值嚴格等於undefined時,默認值纔會生效,否則爲數組屬性值

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

如果默認值是一個表達式,這個表達式只有用到時纔會求值

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

let [x = f()] = [1]; // 1,這裏的x能直接取到1,所以函數f根本不會執行

2、對象的解構賦值

let {foo, bar} = { foo: "aaa", bar: "bbb"};
// 變量名與屬性名不一致時
var { foo: baz } = { foo: 'aaa', bar: 'bbb' };
 // baz: 'aaa', foo: foo is not defined; foo是匹配的模式,baz纔是變量。
let { first: f, last: l } = { first: 'hello', last: 'world' }; 
// f: 'hello', l: 'world'

嵌套的對象的解構賦值:

var node = {
	loc: {
        start: {
            line: 1,
            column: 5
        }
    }
};
var {loc, loc: {start}, loc: {start: {line}}} = node;
console.log(loc, start, line); 
// {start: {…}},start: {line: 1, column: 5}, 1
let obj = {
   p: [
       'hello',
       {y: 'world'}
   ]
};

let {p, p: [x, {y}]} = obj;
console.log(p); // (2) ["hello", {y: "world}]
console.log(x); // "hello"
console.log(y); // "world"

對象的解構也可以制定默認值:

var {x = 3} = {};// x = 3
var {x, y = 5} = {x: 1};// x = 1 ,y = 5
var {x: y = 3} = {}; // y = 3

默認值生效的條件是,對象的屬性嚴格等於undefined。

let arr = [1, 2, 3];
let {0: first, [arr.length - 1]: last} = arr; // []這種寫法屬於“屬性名錶達式”
console.log(first, last); // 1 3

3、用途

3.1 交換變量的值

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

3.2 從函數返回多個值,取值很方便

// 返回數組
function example() {
   return [1, 2, 3];
}

let [a, b, c] = example();
console.log(a, b, c); // 1 2 3

// 返回對象
function example2() {
   return {
       foo: 1,
       bar: 2
   }
}

let {foo, bar} = example2();
console.log(foo, bar); // 1 2

3.3 函數參數的定義

function f([x, y, z]) {}
f([1,2,3]);

function f2({x, y, z}) {}
f2({z: 3, y: 2, x: 1});

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]

3.5 函數參數默認值

3.6 遍歷Map

for (let [key, value] of map)

3.7導入模塊時制定方法

[參考文獻]:ES6標準入門(第三版)

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