Handling from B station technical egg teacher video
The full text is about 500 words and takes about 5 minutes to read
Temporary variable method
When I was in college, THE first way I learned to exchange variables was to imagine that there were three bottles on the table: Coke in bottle A, Sprite in bottle B, and empty bottle C. It was easy to imagine that a poured into C, B poured into A, and C poured into B to complete the exchange
let a = 0, b = 1;
let c = a;
a = b;
b = c;
console.log(a, b); / / 1 0
Copy the code
Addition and subtraction
The idea is similar to a classic thinking question often encountered in the interview. You have a 4L bottle and a 9L bottle, how do you get 6L water from a pond? The process is as follows (unit: L) 0/0/9 4/5 0/5 4/1 0/1 1/0 1/9 4/6
let a = 0, b = 1;
a = a + b;
b = a - b;
a = a - b;
console.log(a, b); / / 1 0
Copy the code
Array method
The idea is relatively simple, by accessing the array to achieve variable exchange
let a = 0, b = 1;
a = [a, b];
b = a[0];
a = a[1];
console.log(a, b); / / 1 0
Copy the code
Object method
The idea is similar to the previous array method, except that the array is replaced by an object
let a = 0, b = 1;
a = {a: b, b: a};
b = a.b;
a = a.a;
console.log(a, b); / / 1 0
Copy the code
Array operation
B = a then a = [b, 0][0]
let a = 0, b = 1;
a = [b, b = a][0];
console.log(a, b); / / 1 0
Copy the code
Bitwise xor method
If the binary bits are identical, 0 is returned. If the binary bits are different, 1 is returned
let a = 0, b = 1;
a = a ^ b;
b = a ^ b;
a = a ^ b
console.log(a, b); / / 1 0
Copy the code
Deconstructing assignment
Through es6 destruct assignment syntax
let a = 0, b = 1;
[a, b] = [b, a];
console.log(a, b); / / 1 0
Copy the code
After the
More methods welcome big guys comment to add
Personal CSS project is under construction