二、遍歷的解構賦值
1. 數組的解構賦值
基本用法
ES6解構:按照一定模式便捷的從對象和數組中提取/賦值
- 便捷性說明
前(ES5)
let a = 1;
let b = 2;
let c = 3;
後(ES6)
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]
不完全解構,失敗部分爲undefined或[]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
- 不合法情況
如果右邊不是數組或者說Iterator可遍歷結構則報錯
// 報錯
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
- 進一步說明?
只要右邊賦值的數據結構具有Iterator接口即可進行解構賦值。
Generator函數
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
默認值
- 解構賦值允許指定默認值
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
- 當賦值undefined纔會生效(ES6使用的是===,所以null則默認值不生效)
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
- 默認值如是表達式,則在使用時纔會用到(非undefined)
function f() {
console.log('aaa');
}
let [x = f()] = [1];
//x=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 { log, sin, cos } = Math;
// 例二
const { log } = console;
log('hello') // hello
- 數組與對象解構的區別
(1)數組是按次序排列進行解構
(2)對象是對應屬性名進行解構
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined
- 對象&數組解構失敗都是undefined
let {foo} = {bar: 'baz'};
foo // undefined
- 對象解構賦值與數組不同
先找到同名屬性,再賦給對應的變量——真正被賦值的是後者,而不是前者。
對象的解構賦值:
let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
- 與數組同樣適用嵌套的對象
(1)p作爲模式不會被賦值
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
(2)p作爲變量賦值
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p // ["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}
- 避免暫時性死區
// 報錯,foo不存在undefined
let {foo: {bar}} = {baz: 'baz'};
- 繼承的屬性一樣可以解構賦值
const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar"
默認值
- 解構賦值指定默認值
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
var {x: y = 3} = {};
y // 3
var {x: y = 3} = {x: 5};
y // 5
var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
- 只有解構對象的屬性值爲undefined才生效(同數組)
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null
- 特殊情況
(1)對已聲明的對象進行解構,需使用()進行賦值,否則會被理解成代碼塊
// 錯誤的寫法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
// 正確的寫法
let x;
({x} = {x: 1});
(2)無意義。解構賦值允許等號左邊模式之中不放置任何變量名
({} = [true, false]);
({} = 'abc');
({} = []);
(3)對數組進行對象解構(數組是特殊的對象)
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
3. 字符串的解構賦值
字符串可以解構賦值,是因爲字符串被轉換成一個類似數組的對象。同時可就數組類型進行屬性解構。
- 實例說明
取元素賦值解構
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
//取屬性值解構
let {length : len} = 'hello';
len // 5
4. 數值和布爾值的解構賦值
解構賦值時
(1)如果有變是數值或布爾值則會轉爲對象
(2)如果是undefined和null則無法轉爲對象
- 實例說明
(1)變量s賦值爲123/true轉換後的對象的toString屬性。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
(2)
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
5. 函數參數的解構賦值
參數數組/對象相對(1)直接進行解構賦值(2)可使用默認值(undefined也觸發)
(1)數組對數組
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
(2)對象對對象,同時使用默認值
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]
6. 圓括號問題
對於編譯器來說,一個式子是模式還是表達式並不明瞭,到解析才知道。帶來的問題是
(1)ES6可能導致解構的歧義
不能使用圓括號的情況
- 變量聲明語句(模式),不能使用圓括號
// 全部報錯
let [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2 } };
- 函數參數(也屬於變量聲明)
// 報錯
function f([(z)]) { return z; }
// 報錯
function f([z,(x)]) { return x; }
- 賦值的模式
// 報錯
[({ p: a }), { x: c }] = [{}, {}];
可以使用圓括號的情況
與不可使用相反。非模式即表達式,則可使用圓括號
- 例子
[(b)] = [3]; // 正確
({ p: (d) } = {}); // 正確
[(parseInt.prop)] = [3]; // 正確
7. 用途
- 交換變量的值
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([1, 2, 3]);
// 參數是一組無次序的值
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
};
- 遍歷Map結構(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) {
// ...
}
Object和map區別只在於鍵的類型,前者字符串,後者可以是任何類型
- 輸入模塊的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");