js two values exchange

First, the general practice

And more common practice is to declare a temporary variable tmp, data exchange process cache. This approach intuitive and easy to understand. However, increases memory usage

var a = 1,
    b = 2,
    tmp;
 
tmp = a;
a = b;
b = tmp;

Second, the arithmetic

, It can be interchanged by skilfully two values ​​during arithmetic skills. However, there is a drawback is that the variable data overflow. Because the range of accuracy that can store digital JavaScript is -253 to 253. Therefore, the addition operation, there will be overflow problems.

var a = 1,
    b = 2;
 
a = a + b; // a = 3, b = 2
b = a - b; // a = 3, b = 1
a = a - b; // a = 2, b = 1

Third, the exclusive-OR operation

Using this technique problem-bit computing, the use of a ^ b ^ b == a characteristic numerical exchange, avoiding the drawbacks caused by the use of arithmetic overflow problem does not occur.

var A =. 1, // binary: 0001 
    B = 2;   // binary: 0010 
 
A = A ^ B; // results: a = 0011, B = 0010 
B = A ^ B; // results: a = 0011, B = 0001 
A = A ^ B; // results: a = 0010, b = 0001

Four, ES6 deconstruction

With syntax features of deconstruction, once and for simple violence, ha ha ha ~
more important point: deconstruction of syntax also applicable to other types of variables are interchangeable. So, deconstruction can be interchanged with a very easy manner.

let a = 1,
    b = 2;
 
[a, b] = [b, a];

Fifth, the use of an array of characteristics exchange

There are a = 1 , 
    b = 2 ; 
 
a = [a, b]; 
b = a [0 ]; 
a = a [1];

 

 

Guess you like

Origin www.cnblogs.com/smile6542/p/11855966.html