一褪尝、數(shù)組的解構(gòu)賦值
1.1、基本用法
ES6 允許按照一定模式從數(shù)組和對象中提取值期犬,然后對變量進行賦值河哑,這被稱為解構(gòu)(Destructuring)
let [a, b, c] = [1, 2, 3]
本質(zhì)上,這種寫法屬于 “模式匹配”龟虎, 只要等號兩邊的模式相同璃谨,左邊的變量就會被賦予對應(yīng)的值。
下面是一些使用嵌套數(shù)組進行解構(gòu)的例子:
let [foo, [[bar], baz]] = [1, [[2], 3]]
console.log(foo) // 1
console.log(bar) // 2
console.log(baz) // 3
let [ , , third] = [1, 2, 3]
console.log(third) // 3
let [x, , y] = [1, 2, 3]
console.log(x) // 1
console.log(y) // 3
let [head, ...tail] = [1, 2, 3, 4]
console.log(head) // 1
console.log(tail) // [2, 3, 4]
let [x, y, ...z] = ['a']
console.log(x) // a
console.log(y) // undefined
console.log(z) // []
如果解構(gòu)不成功鲤妥,變量的值就等于 undefined
let [foo] = [] // undefined
let [bar, foo] = [1]
console.log(foo) // undefined
另一種情況是不完全解構(gòu)佳吞,這種情況下解構(gòu)依然可以成功
let [x, y] = [1, 2, 3]
console.log(x) // 1
console.log(y) // 2
let [a, [b], d] = [1, [2, 3], 4]
console.log(a) // 1
console.log(b) // 2
console.log(d) // 4
如果等號的右邊不是數(shù)組(嚴格來說不是可遍歷的結(jié)構(gòu)),那么將報錯
// 報錯
let [foo] = 1
let [foo] = false
let [foo] = NaN
// ...
上面的語句都會報錯旭斥,因為等號右邊的值或是轉(zhuǎn)為對象以后不具備 Iterator 接口容达,或是本身就不具備 Iterator 接口
對于 Set 接口,也可以使用數(shù)組的解構(gòu)賦值
let [x, y, z] = new Set(['a', 'b', 'c'])
x // a
事實上垂券,只要某種數(shù)據(jù)結(jié)構(gòu)具備 有 Iterator 接口花盐,都可以采用數(shù)組形式的解構(gòu)賦值
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()
console.log(sixth) // 5
fibs 是一個 Generator 函數(shù),原生具有 Iterator 接口菇爪。解構(gòu)賦值會依次從這個接口中獲取值算芯。
1.2、默認值
解構(gòu)賦值允許指定默認值
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內(nèi)部使用 嚴格相等運算符 (===) 判斷一個位置是否有值凳宙。所以熙揍,如果一個數(shù)組成員不嚴格等于 undefined,默認值是不會生效的氏涩。
let [x = 1] = [undefined]
console.log(x) // 1
let [y = 1] = [null]
console.log(y) // null
如果默認值是一個表達式届囚,那么這個表達式是惰性求值有梆,即只有在用到時才會求值。
function f() {
console.log('hi')
}
let [x = f()] = [1]
以上函數(shù)不會執(zhí)行意系,因為x 能夠取到值泥耀。
默認值可以應(yīng)用解構(gòu)賦值的其他變量,但該變量必須已經(jīng)聲明蛔添。
let [x = 1, y = x] = [] // x = 1 y = 1
let [x = y, y = 1] = [] // ReferenceError
最后一個表達式會報錯痰催,因為 x 用到默認值 y 時, y 還沒有聲明迎瞧。
二夸溶、對象的解構(gòu)賦值
解構(gòu)不僅可以用于數(shù)組,還可以用于對象
let { foo, bar } = { foo: 'aaa', bar: 'bbb' }
console.log(foo) // aaa
console.log(bar) // bbb
對象的解構(gòu)與數(shù)組有一個重要的不同凶硅。對象的屬性沒有次序缝裁,變量必須與屬性同名才能取到正確的值。
let { baz } = { foo: 'aaa' }
console.log(baz) // undefined
如果想要變量名與屬性名不一致咏尝,必須寫成下面這樣压语。
let obj = { first: 'hello', last: 'world' }
let { first: f, last: l } = obj
console.log(f) // hello
console.log(l) // world
實際上說明,對象的解構(gòu)賦值是下面形式的簡寫
// let { foo, bar } = { foo: 'aaa', bar: 'bbb' }
let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' }
也就是說编检,對象的解構(gòu)賦值的內(nèi)部機制是先找到同名屬性胎食,然后再賦值給對應(yīng)的變量。真正被賦值的是后者允懂,而不是前者厕怜。
let { foo: baz } = { foo: 'aaa', bar: 'bbb' }
console.log(baz) // aaa
console.log(foo) // error: foo is not defined
foo 是匹配的模式,baz 才是變量蕾总。真正被賦值的是變量 baz粥航,而不是模式 foo。
與數(shù)組一樣生百,解構(gòu)也可以用于嵌套結(jié)構(gòu)的對象递雀。
let obj = {
p: [
'Hello',
{ y: 'World' }
]
}
let { p: [x, { y }] } = obj
console.log(x) // Hello
console.log(y) // World
注意,這時 p 是模式蚀浆,不是變量缀程,因為不會被賦值。
如果 p 也要作為變量復(fù)制市俊,可以寫成下面這樣
let {p, p: [x, {y}] } = obj
console.log(p) // [ 'Hello', { y: 'World' }]
下面是另外一個例子:
var node = {
loc: {
start: {
line: 1,
column: 5
}
}
}
var { loc, loc: { start }, loc: { start: { line }} } = node
console.log(line) // 1
console.log(start) // { line: 1, column: 5 }
console.log(loc) // { start: { line: 1, column: 5 }}
下面是 嵌套賦值的例子:
let obj = {}
let arr = []
({ foo: obj.prop, bar: arr[0]}) = { foo: 123, bar: true}
console.log(obj) // { prop: 123 }
console.log(arr) // [true]
同樣類似的對象的解構(gòu)也可以指定默認值杨凑,生效的條件依然是,屬性值嚴格等于 undefined
如果解構(gòu)失敗摆昧,變量的值就等于 undefined
let { foo } = { bar: 'baz' }
console.log(foo) // undefined
如果解構(gòu)模式是嵌套的對象撩满,而且子對象所在的副屬性不存在,那么就會報錯
// 報錯
let { foo: { bar } } = { baz: 'baz' }
因為 foo 此時等于 undefined,而取子屬性就會報錯伺帘。
如下代碼:
let _tmp = { bar: 'aaa' }
_tmp.foo.bar // 報錯
如果要將一個已經(jīng)聲明的變量用于解構(gòu)賦值昭躺,必須非常小心
// 錯誤的寫法
let x;
{x} = {x: 1}
// SyntaxError: syntax error
上面的寫法會報錯,因為 JavaScript 引擎會將 {x} 理解成一個代碼塊曼追,從而發(fā)生語法錯誤窍仰。
主要不講大括號寫在行首,米面 JavaScript 將其解釋為 代碼塊礼殊,才能解決這個問題。
// 正確的寫法
let x;
({x} = {x: 1})
console.log(x)
對象的解構(gòu)賦值可以很方便地將現(xiàn)有對象的方法賦值到某個變量针史。
let { log, sin, cos } = Math
由于數(shù)組本質(zhì)是特殊的對象晶伦,因此可以對數(shù)組進行對象屬性的解構(gòu)。
let arr = [1, 2, 3]
let { 0: first, [arr,length -1]: last } = arr
console.log(first) // 1
console.log(last) // 3
三啄枕、字符串的解構(gòu)賦值
字符串也可以解構(gòu)賦值婚陪。因為此時字符串被轉(zhuǎn)換成一個類似數(shù)組的對象
const [a, b, c, d, e] = 'hello'
console.log(a) // h
console.log(e) // o
類似數(shù)組的對象都有一個 length 屬性,因此可以對這個屬性進行解構(gòu)賦值频祝。
let { length: len } = 'hello'
console.log(len) // 5
四泌参、數(shù)值和布爾值的解構(gòu)賦值
解構(gòu)賦值時,如果等號右邊是數(shù)值和布爾值常空,則會先轉(zhuǎn)為對象
let {toString: s} = 123
console.log(s === Number.prototype.toString) // true
let {toString: s} = true
console.log(s === Boolean.prototype.toString) // true
解構(gòu)賦值的規(guī)則是沽一,只要等號右邊的值不是對象或數(shù)組,就先將其轉(zhuǎn)為對象漓糙。由于 undefined 和 null 無法轉(zhuǎn)為對象铣缠,所以對它們進行解構(gòu)賦值時都會報錯。
五昆禽、函數(shù)參數(shù)的解構(gòu)賦值
函數(shù)的參數(shù)也可以使用解構(gòu)賦值蝗蛙。
function add([x, y]) {
return x + y
}
add([1, 2]) // 3
[[1, 2], [3, 4]].map(([a, b]) => a + b)
// [3, 7]
函數(shù)參數(shù)的解構(gòu)也可以使用默認值
function move({x = 0, y = 0} = {}) {
return [x, y]
}
move({x: 3, y: 8}) // [3, 8]
move({}) // [0, 0]
move() // [0, 0]
類似的 undefined 就會觸發(fā)函數(shù)參數(shù)的默認值。
六醉鳖、圓括號問題
解構(gòu)賦值雖然很方便捡硅,但是解析起來并不容易。對于編譯器來說盗棵,一個式子到底是模式還是表達式壮韭,沒有辦法從一開始就知道,必須解析到(或解析不到)等號才知道漾根。
ES6 的規(guī)則是泰涂,只要有可能導(dǎo)致解構(gòu)的歧義,就不得使用圓括號辐怕。
但是逼蒙,這條規(guī)則實際上不那么容易辨別,處理起來相當麻煩寄疏。因此建議是牢,只要有可能僵井,就不要在模式中放置圓括號
6.1、不能使用圓括號的情況
以下三種解構(gòu)賦值不得使用圓括號:
- 變量聲明語句
// 全部報錯
let [(a)] = [1]
let {x: (c)} = {}
let ({x: c}) = {}
let {(x: c)} = {}
let {(x): c} = {}
let {o: ({ p: p }) } = {o: {p: 2} }
變量聲明語句驳棱,模式不能使用圓括號
- 函數(shù)參數(shù)
函數(shù)參數(shù)也屬于變量聲明批什,因此不能使用圓括號。
// 報錯
function f([ (2) ]) { return z }
function f([z, (x)]) { return x}
- 賦值語句的模式
// 報錯
({p: a}) = {p: 42}
([a]) = [5]
上面代碼將整個模式放在圓括號之中社搅,導(dǎo)致報錯
// 報錯
[ ({p: a}), {x: c}] = [{}, {}]
上面代碼將一部分模式放在圓括號之中驻债,導(dǎo)致報錯
6.2、可以使用圓括號的情況
可以使用圓括號的情況只有一種形葬,賦值語句的非模式部分可以使用圓括號合呐。
[(b)] = [3] // 模式是取數(shù)組的第 1 個成員,跟圓括號無關(guān)
( {p: (d)} = {}) // 模式 是 p 而不是 d
[(parseInt.prop)] = [3] // 與第一行語句的性質(zhì)一樣
上面 3 行語句都可以正確執(zhí)行笙以,因為它們都是賦值語句淌实,而不是聲明語句,另外它們的圓括號都不屬于模式的一部分猖腕。
七拆祈、主要用途
變量的解構(gòu)賦值用途很多
1. 交換變量的值
let x = 1
let y = 2
[x, y] = [y, x] // 這種方式簡潔易讀,語義清晰
2. 從函數(shù)返回多個值
函數(shù)只能返回一個值倘感,如果返回多個值放坏,可以通過 對象 或 數(shù)組的方式。有了解構(gòu)賦值侠仇,取出這些值就非常方便轻姿。
// 返回一個數(shù)組
function example1() {
return [1, 2, 3]
}
let [a, b ,c] = example1()
// 返回一個對象
function example2() {
return {
foo: 1,
bar: 2
}
}
let { foo, bar} = example2()
3. 函數(shù)參數(shù)的定義
解構(gòu)賦值可以方便地將一組參數(shù)與變量名對應(yīng)起來
// 參數(shù)是一組有次序的值
function f([x, y, z]) {
console.log(x, y, z)
}
f([1, 2, 3])
// 參數(shù)是一組無次序的值
function fn({x, y, z}) {
console.log(x, y, z)
}
fn({x: 1, z: 2, y: 3})
4. 提取 JSON 數(shù)據(jù)
解構(gòu)賦值對提取 JSON 對象中的數(shù)據(jù)尤其有用
let jsonData = {
id: 45,
status: 'ok',
data: [111, 222]
}
let {id, status, data: number} = jsonData
console.log(id, status, number)
5. 函數(shù)參數(shù)的默認值
function fn({foo = 'default', bar = 'default bar'}) {
console.log(foo, bar)
}
fn({foo: 'kkk'})
6. 遍歷 Map 解構(gòu)
任何部署了 Iterator 接口的對象都可以用 for...of 循環(huán)遍歷。Map 結(jié)果原生支持 Iterator接口逻炊,配合變量的解構(gòu)賦值獲取鍵名和鍵值就非常方便
var map = new Map()
map.set('first', 'hello')
map.set('last', 'world')
for(let [key, value] of map) {
console.log(`${key} is: ${value}`)
}
// 獲取鍵名
for (ley [key] of map) {
// ...
}
// 獲取鍵值
for (let [, value] of map) {
// ...
}
7. 輸入模塊的指定方法
加載模塊時贫贝,往往需要指定輸出的方法恒傻。解構(gòu)賦值使得輸出語句非常清晰鹰霍。
const { join, resolve } = require('path')