我刚刚注意到,以下代码(在let [one, two] = [1, 2]之后没有立即引用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
有人能解释为什么这样的行为存在吗?谢谢!
发布于 2018-03-15 06:22:03
因为它被解析成这样:
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,如果它出了问题,就会出现这样的情况。
https://stackoverflow.com/questions/49292669
复制相似问题