在 ECMAScript 5 及早期版本中,从对象和数组中获取数据会导致很多冗余代码:1
2
3
4
5
6
7
8
9
10let options = {
repeat: true,
save: false
}
let repeat = options.repeat,
save = options.save
console.log(repeat, save)
// true false
Object Destrcturing
1 | let node = { |
destructuring 也可以为已经初始化过的变量赋值:1
2
3
4
5
6
7
8
9
10
11let node = {
type: "Identifier",
name: "foo"
}
let type = "Literal", name = 5;
({ type, name } = node)
console.log(type, name)
// Identifier foo
({ type, name } = node)
外面的小括号是必须的。只有大括号的话,大括号会被看成语句块,而语句块不能位于等号左边。
destructuring 赋值语句可以出现在代码的任何位置:1
2
3
4
5
6
7
8
9
10
11
12
13let node = {
type: "Identifier",
name: "foo"
}
let type = "Literal", name = 5;
function outputInfo(value) {
console.log(value === node)
}
outputInfo({ type, name } = node) // true
console.log(type, name) // Identifier foo
默认值1
2
3
4
5
6
7
8
9let node = {
type: "Identifier",
name: "foo"
}
let { type, name, value } = node
console.log(type, name, value)
// Identifier foo undefined
1 | let node = { |
嵌套对象的 destructuring1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19let node = {
type: "Identifier",
name: "foo",
loc: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 4
}
}
}
let { loc: { start }} = node
console.log(start.line, start.column)
// 1 1
Array Destructuring
1 | let colors = ["red", "green", "blue"] |
ECMAScript 5 中的变量互换:1
2
3
4
5
6
7let a = 1, b = 2, tmp;
tmp = a
a = b
b = tmp
console.log(a, b) // 2 1
ECMAScript 6 中的变量互换:1
2
3
4
5let a = 1, b = 2;
[ a, b ] = [ b, a ]
console.log(a, b) // 2 1
嵌套数组:1
2
3
4
5let colors = [ "red", [ "green", "lightgreen" ], "blue" ]
let [ firstColor, [ secondColor ] ] = colors
console.log(firstColor, secondColor) // red green
Rest Items:1
2
3
4
5
6
7
8let colors = [ "red", "green", "blue" ]
let [ firstColor, ...restColors ] = colors
console.log(firstColor) // "red"
console.log(restColors.length) // 2
console.log(restColors[0]) // green
console.log(restColors[1]) // blue
在 ECMAScript 5 中,可以使用 concat()
方法创建某个数组的克隆:1
2
3
4
5var colors = [ "red", "green", "blue" ]
var clonedColors = colors.concat()
console.log(clonedColors)
// [ 'red', 'green', 'blue' ]
ECMAScript 6 中则可以使用 rest items 语法创建克隆:1
2
3
4
5let colors = [ "red", "green", "blue" ]
let [ ...clonedColors ] = colors
console.log(clonedColors)
// [ 'red', 'green', 'blue' ]