我正在修改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]
值的数组,该数组将被解构。结果,两个变量被切换。