简体   繁体   中英

Destructing assignment to swap the values in ES6

I am revising JavaScript and came to following ES6 example.

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

Not able to figure out how this is working, as we have assignment operator with both side arrays.

Destructuring basically separates an array or an object into separate variables. That is what happens on the left side. Exemple:

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"

On the right side, you are creating an array with the values [b, a] which will be destructured. As a result, the two variables are switched.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM