Kev*_*ian 1 javascript destructuring ecmascript-6
我只是注意到以下代码,如果没有立即引用oneafter 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)Run Code Online (Sandbox Code Playgroud)
然而,简单地one在声明和交换之间添加一个 not-used突然允许代码,但不正确:
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' insteadRun Code Online (Sandbox Code Playgroud)
而下面的代码给出了预期的交换效果
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么存在这种行为吗?谢谢!
在第一行添加一个分号,因为解释器假定第 1 行和第 2 行声明一起发生,并且one(and two) 尚未定义:
let [one, two, three] = [1, 2, 3];
[one, two] = [two, one]
console.log(one, two)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
600 次 |
| 最近记录: |