关于ES6数组解构和交换的有趣行为

时间:2018-03-15 06:15:18

标签: javascript ecmascript-6 destructuring

我刚刚注意到以下代码,在one之后没有立即引用let [one, two] = [1, 2],尝试[one, two] = [two, one]会崩溃:



let [one, two, three] = [1, 2, 3]
[one, two] = [two, one] // CRASH! one is not defined
console.log(one, two)




但是,只需在声明和交换之间添加一个未使用的one突然允许代码,但不正确:



let [one, two, three] = [1, 2, 3]
one // inserted here
[one, two] = [two, one] // no longer crashes! but not actually swapping
console.log(one, two) // should be '2 1', but shows '1 2' instead




以下代码给出了预期的交换效果



var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1




有人可以解释为什么存在这种行为吗?谢谢!

2 个答案:

答案 0 :(得分:4)

在第1行添加分号,因为解释器假定第1行和第2行声明一起发生,one(和two)尚未定义:



let [one, two, three] = [1, 2, 3];
[one, two] = [two, one]
console.log(one, two)




答案 1 :(得分:1)

因为它解析如下:

 let [one, two, three] = [1, 2, 3][one, two] = [one, two]

为了使它成功,总是用parens来解释分配任务:

 let [one, two, three] = [1, 2, 3];
 ([one, two] = [two, one]);
 console.log(one, two);

永远不要相信ASI,有些情况会出现问题。