SoFunction
Updated on 2025-03-08

JS implementation does not use intermediate variable temp to implement two variables worth exchanging methods

1. Use addition and subtraction;

var a=1;
var b=2;
a=a+b;
b=a-b;
a=a-b;

2. Use multiplication and division (multiple and division are more like mapping from addition and subtraction to multiplication and division operations)

var a=1;
var b=2;
 a = a * b;
 b = a / b;
 a = a / b;

Note: This method can exchange variables of integer and floating-point numerical values, but when dealing with floating-point typing, there may be a loss of accuracy. Moreover, b cannot be 0 when multiplication and division;

3. Flexibility of using arrays

var a=1;
var b=2;
a=[b,b=a][0];

Summarize

The above is the method of exchanging JS implementation without the intermediate variable temp. Implementing two variables is worth exchanging. I hope it will be helpful to everyone. If you have any questions, please leave me a message. The editor will reply to everyone in time!