解构赋值以交换 ES6 中的值

Destructing assignment to swap the values in ES6

我正在修改 JavaScript 并开始关注 ES6 示例。

let a = 8, b = 6;
// change code below this line
[a,b] = [b,a];
// change code above this line
console.log(a); // a is 6
console.log(b); // b is 8

无法弄清楚这是如何工作的,因为我们对两侧数组都有赋值运算符。

解构基本上将一个数组或一个对象分离成单独的变量。这就是左侧发生的情况。例子:

var foo = [1, 2]
var [a, b] = foo; // creates new variables a and b with values from the array foo

console.log(a); // prints "1"
console.log(b); // prints "2"

在右侧,您正在创建一个数组,其值 [b, a] 将被解构。结果两个变量互换了。