Variable exchange method: 1. With the help of the third variable c, the syntax "c=a;a=b;b=c;", so that the values of variables a and b can be interchanged; 2. Using arrays Subscript reassignment, the syntax is "a=[a,b];b=a[0];a=a[1];"; 3. Use the destructuring assignment of the array, the syntax is "[a, b]=[b, a];".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Method to implement variable exchange in es6
Method 1: With the help of the third variable
There are two variables a and b, and variable exchange can be achieved with the help of a third variable c.
First assign the a value to c
, then assign the b value to a
Finally assign Assign the c value to b
var a=1; var b=2; var c=a; a=b; b=c; console.log(a,b)//2,1
Method 2: Reassign the value using the array subscript
var a = 3, b = 4; a = [a, b]; b = a[0]; a = a[1]; console.log(a,b)
Method 3: Use the destructuring assignment of the array to exchange the value of the variable
var a = 3, b = 4; [a, b] = [b, a]; console.log(a,b)
[Related recommendations: javascript video Tutorial、web front-end】
The above is the detailed content of How to implement variable exchange in es6. For more information, please follow other related articles on the PHP Chinese website!