关于 ES6 数组解构和交换的有趣行为
Interesting behavior about ES6 array destructuring and swapping
我刚刚注意到下面的代码,在 let [one, two] = [1, 2]
之后没有立即引用 one
,尝试 [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
有人可以解释为什么存在这种行为吗?谢谢!
在第 1 行添加一个分号,因为解释器假定第 1 行和第 2 行声明一起发生,并且 one
(和 two
)尚未定义:
let [one, two, three] = [1, 2, 3];
[one, two] = [two, one]
console.log(one, two)
因为它是这样解析的:
let [one, two, three] = [1, 2, 3][one, two] = [one, two]
为了让它工作,总是用括号包围解构赋值:
let [one, two, three] = [1, 2, 3];
([one, two] = [two, one]);
console.log(one, two);
永远不要相信 ASI,如果它出错了,也会有这样的情况。
我刚刚注意到下面的代码,在 let [one, two] = [1, 2]
之后没有立即引用 one
,尝试 [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
有人可以解释为什么存在这种行为吗?谢谢!
在第 1 行添加一个分号,因为解释器假定第 1 行和第 2 行声明一起发生,并且 one
(和 two
)尚未定义:
let [one, two, three] = [1, 2, 3];
[one, two] = [two, one]
console.log(one, two)
因为它是这样解析的:
let [one, two, three] = [1, 2, 3][one, two] = [one, two]
为了让它工作,总是用括号包围解构赋值:
let [one, two, three] = [1, 2, 3];
([one, two] = [two, one]);
console.log(one, two);
永远不要相信 ASI,如果它出错了,也会有这样的情况。