# 【金秋打卡】第24天 再学JavaScript ES(6-10)全版本语法大全

2022.11.17 22:38 292浏览

ES6 允许按照一定模式，从数组和对象中提取值，对变量进行赋值，这被称为解构

``````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]
tail // [2, 3, 4]

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

``````

``````let [foo] = []
let [bar, foo] = [1]
``````

``````let [x, y] = [1, 2, 3]
x // 1
y // 2

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

``````

``````// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

``````

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

``````

``````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
``````

fibs是一个 Generator 函数，原生具有 Iterator 接口，解构赋值会依次从这个接口获取值

``````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] = [undefined];
x // 1

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

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

let [x = f()] = [1];
``````

``````let x;
if ([1][0] === undefined) {
x = f();
} else {
x = [1][0];
}

``````

``````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
``````

0人点赞

Web前端工程师

1

0

### 风间影月说签约讲师

51篇手记，涉及Java、MySQL、Redis、Spring等方向

### Tony Bai 说签约讲师

151篇手记，涉及Go、C、Java、Python等方向

• 推荐
• 评论
• 收藏
• 共同学习，写下你的评论

0/150