解构赋值

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let [a, b, c] = [1, 2, 3]
let [foo, [[bar], baz]] = [1, [[2], 3]]

let [, , third] = ["foo", "bar", "baz"]
third //'baz'
let [x, , y] = [1, 2, 3]
x, y //1, 3

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

let [x, y, ...z] = ["a"]
x //a
y //undefined
z //[]

let [x, y, z] = new Set(["a", "b", "c"])
x //'a'

不完全解构也会解构成功

1
2
3
4
5
6
7
let [x, y] = [1, 2, 3]
x, y //1, 2

let [a, [b], d] = [1, [2, 3], 4]
a //1
b //2
d //4

只要具备 Iterator 接口,都可以进行解构赋值

1
2
3
4
5
6
7
8
9
10
function* fibs() {
let a = 0,
b = 1
while (true) {
yield a
;[a, b] = [b, a + b]
}
}
let [first, second, third, fourth, fifth, sixth] = fibs()
sixth //5

默认值

1
2
3
4
5
6
7
let [foo = "true"] = []
foo //true

let [x, y = "b"] = ["a"] //x = a, y = b
let [x, y = "b"] = ["a", undefined] //x = a, y = b;

let [x = 1] = [null] //x = null, null 不严格等于 undefined

如果默认值是一个表达式,那么这个表达式是 lazy evaluation 的,只有在用到时才会求值。

1
2
3
4
5
function f() {
console.log("f is run")
}
let [x = f()] = [1] //f 不会执行
let [x = y, y = 1] = [] //ReferenceError

对象的解构赋值

1
2
3
4
5
6
7
8
let { foo, bar } = { foo: "aaa", bar: "baz" }
foo //'aaa'
bar //'baz'
let { baz } = { foo: "aaa", bar: "baz" }
baz //undefined

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

前者是匹配模式,后者是变量。

1
let { foo: foo, bar: bar } = { foo: "aaa", bar: "baz" }

解构的嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
let obj = {
p: ["hello", { y: "world" }],
}
let {
p: [x, { y }],
} = obj
//x : 'hello', y : 'world'

var node = {
loc: {
start: {
line: 1,
column: 5,
},
},
}
var {
loc,
loc: { start },
loc: {
start: { line },
},
} = node
line //1
loc //Object {start : Object}
start //Object {line : 1, column : 5}

let x
;({ x } = { x: 1 }) //避免 JavaScript 解释为代码块

如果解构失败,变量的值等于 undefined

解构的用途

交换变量的值

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

从函数返回多个值

1
2
3
4
5
6
7
8
9
10
11
function example1() {
return [1, 2, 3]
}
let [a, b, c] = example1()
function example2() {
return {
foo: 1,
bar: 2,
}
}
let { foo, bar } = example2()

函数参数的定义

1
2
3
4
function f([x, y, z]) {}
f([1, 2, 3])
function f1({ x, y, z }) {}
f1({ z: 3, y: 1, x: 1 })

提取 JSON 数据

1
2
3
4
5
6
let jsonData = {
id: 32,
status: "OK",
data: [332, 452],
}
let { id, status, data: number } = jsonData