有关ES6阵列解构和交换的有趣行为 [英] Interesting behavior about ES6 array destructuring and swapping

查看:76
本文介绍了有关ES6阵列解构和交换的有趣行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just noticed that the following code, without immediately referencing one after let [one, two] = [1, 2], trying [one, two] = [two, one] would crash:

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

但是,仅在声明和交换之间添加未使用的one会突然允许该代码,但错误地是:

However, simply adding a not-used one between the declaration and swapping suddenly allows the code, but incorrectly:

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

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

Whereas the below code gives the expected swapping effect

var a = 1;
var b = 3;

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

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

Can someone explain why such behavior exists? Thanks!

推荐答案

在第一行添加分号,因为解释器假定第1行和第2行声明同时出现,而one(和two)不是尚未定义:

Add a semicolon to the 1st line, because the interpreter assumes that lines 1 and 2 declarations happen together, and one (and two) is not defined yet:

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

这篇关于有关ES6阵列解构和交换的有趣行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆