When we write programs, we usually encounter situations where the values of two numbers are exchanged. Then we can solve them by the following methods, or we can encapsulate them into functions and call them directly when we need to use them.
Method 1:
Solve with the exclusive OR operator (^) without using the third variable
<script>
var a=1;
var b=2;
a=a^b;
b=a^b;
a=a^b;
console.log(a,b);
</script>
Convert two numbers into binary, compare them bitwise, take 0 for the same, and take 1 for the same, and get the third value; in this way, the following expressions are calculated to achieve the effect of exchanging values;
the process is as follows:
a=a ^b
a:0001
b:0010
result: 0011–>a=3
b=a^b
a:0011
b:0010
result: 0001–>b=1
a=a^b;
a:0011
b:0001
result: 0010 -->a=2
Method 2: No third-party variables (addition and subtraction);
<script>
var a=2;
var b=3;
a=a+b; //表达式1
b=a-b; //表达式2
a=a-b; //表达式3
console.log(a,b);
</script>
The above expression can be converted into:
b=expression1-b=(a+b)-b=a; //result 1
a=(a+b)-result 1=(a+b)-a= b;
exchange values through the above calculation methods
Method 3: Without the help of third-party variables (multiplication and division)
<script>
var a=2;
var b=3;
a=a*b;
b=a/b;
a=a/b;
console.log(a,b);
</script>
The calculation process is similar to method two;
method four: use the third variable
<script>
var a = 4;
var b = 5;
var temp;
temp = a;
a = b;
b = temp;
console.log(a,b);
</script>
Method 5: Use ES6 to deconstruct without using the third variable
<script>
var a=5;
var b=6;
[a,b]=[b,a];
console.log(a,b);
</script>
Method 6: With the aid of the third variable,
with the aid of an array, store two variables, and use the characteristics of the array to exchange their values
<script>
var a=6;
var b=7;
var res=[a,b];
a=res[1];
b=res[0];
console.log(a,b);
</script>