Home > Article > Web Front-end > 10 ways to exchange values in JS (share)
In the development process, we need to exchange values. Generally we use a simple solution: "temporary variables". But there is a better way, and not just one, there are many. Sometimes we search for solutions online, copy and paste them when we find them, but never think about how this small piece of code works. Now it's time to learn how to exchange values easily and efficiently.
The simplest one is first.
function swapWithTemp(num1,num2){ console.log(num1,num2) var temp = num1; num1 = num2; num2 = temp; console.log(num1,num2) } swapWithTemp(2.34,3.45)
You can also use some mathematical magic to exchange values.
function swapWithPlusMinus(num1,num2){ console.log(num1,num2) num1 = num1+num2; num2 = num1-num2; num1 = num1-num2; console.log(num1,num2) } swapWithPlusMinus(2.34,3.45)
Let’s see how it works. We get the sum of two numbers on line 4. Now, if one number is subtracted from the sum, then the other number is correct. This is what line 5 does. Subtracting num2
from the sum stored in the num1
variable results in the original num1
value stored in num2
. Similarly, the value of num2
is obtained in num1
on line 6.
Caution: There is also a one-liner alternative to
and -
, though. . .
It goes like this:
function swapWithPlusMinusShort(num1,num2){ console.log(num1,num2) num2 = num1+(num1=num2)-num2; console.log(num1,num2) } swapWithPlusMinusShort(2,3)
The above code gives the expected result. The expression in ()
stores num2
in num1
and then subtracts num1 - num2
, in addition to subtracting Does nothing except num2 - num2 = 0
, hence the result. But when working with floating point numbers, you'll see some unexpected results.
Try to execute the following code and see the result:
function swapWithPlusMinusShort(num1,num2){ console.log(num1,num2) num2 = num1+(num1=num2)-num2; console.log(num1,num2) } swapWithPlusMinusShort(2,3.1)
Just by using the
operator Achieve the same result using
and -
simultaneously.
Look at the code below:
function swapWithPlus(num1,num2){ console.log(num1,num2) num2 = num1 + (num1=num2, 0) console.log(num1,num2) } //Try with - operator swapWithPlus(2.3,3.4)
The above code is valid, but at the expense of readability. In ()
on line 4, we assign num1
to num2
, and 0
next to it is the return value. In short, the operation logic of line 4 is as follows:
num2 = num1 + 0 => num2 = num1.
So we get the correct result.
Note: Some JavaScript engines may optimize the above code to ignore 0
.
Let’s do more tricks with the *
and /
operators.
The principle is the same as the previous method, but there are some minor problems.
function swapWithMulDiv(num1,num2){ console.log(num1,num2) num1 = num1*num2; num2 = num1/num2; num1 = num1/num2; console.log(num1,num2) } swapWithMulDiv(2.34,3.45)
Same as the previous method. First get the product of the two numbers and store them in num1
. Then on line 5, divide num2
by this result to get the first number, then repeat the process to get the second number.
Now you have become a "mathematician".
But where is the little problem?
Let's try it out:
function swapWithMulDiv(num1,num2){ console.log(num1,num2) num1 = num1*num2; num2 = num1/num2; num1 = num1/num2; console.log(num1,num2) } //试着改变数字的值,看看会发生什么 swapWithMulDiv(2.34,0)
Instead of swapping our values we get a weird NaN
, what's going on. If you remember elementary school math class, you'll remember not to divide by 0 because that doesn't make sense.
Then look at other problems with this approach, look at the following code:
function swapWithMulDiv(num1,num2){ console.log(num1,num2) num1 = num1*num2; num2 = num1/num2; num1 = num1/num2; console.log(num1,num2) } //看看会发生什么 swapWithMulDiv(2.34,Infinity)
Yes, it’s NaN again. Because you can't use Infinity
to remove any value, it's undefined.
But I want to try again:
function swapWithMulDiv(num1,num2){ console.log(num1,num2) num1 = num1*num2; num2 = num1/num2; num1 = num1/num2; console.log(num1,num2) } //会怎样呢 swapWithMulDiv(2.34,-Infinity)
-Infinity The result is the same as the previous code, for the same reason.
It turns out that even if you are an excellent "mathematician", there are times when you are powerless.
Here is a shorter version of the value exchange using *
and /
, still having the same problem:
function swapWithMulDivShort(num1,num2){ console.log(num1,num2) num2 = num1*(num1=num2)/num2; console.log(num1,num2) } swapWithMulDivShort(2.3,3.4)
The code above is similar to Shorter code when swapping
and -
. Assign num2
to num1
, and then the calculation logic in line 4 is as follows:
num2 = num1 * num2 / num2 => num2 = num1
In this way, the two values are interchanged.
function swapWithMul(num1,num2){ console.log(num1,num2) num2 = num1 * (num1=num2, 1) console.log(num1,num2) } //Try with / and ** operator swapWithMul(2.3,3.4)
The above program is valid, but it sacrifices readability. In ()
on line 4, we assign num1
to num2
, and the 1
next to it is the return value. In a nutshell, the logic of line 4 looks like this:
num2 = num1 * 1 => num2 = num1
This gives you the result.
XOR is used to perform binary bit operations. Its result is 1 when there are two different inputs and 0 otherwise.
Y | X^Y | |
---|---|---|
1 | 0 | |
0 | 1 | |
1 | 1 | |
0 | 0 |
X | Y | XNOR |
---|---|---|
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 1 |
先了解其工作原理:
function swapWithXNOR(num1,num2){ console.log(num1,num2) num1 = ~(num1^num2); num2 = ~(num1^num2); num1 = ~(num1^num2); console.log(num1,num2) } //可以试试负值 swapWithXNOR(10,1)
10 的 4 位二进制数 -> 1010
1 的 4 位二进制数 -> 0001
第 4 行:
num1 = ~(num1 ^ num2) => ~(1010 ^ 0001) =>~(1011) => ~11 => -12
由于这是一个负数,所以需要将其转换回二进制并计算 2 的补码来获取十进制值,例如:
-12 => 1100 => 0011 + 1 => 0100
第 5 行:
num2 = ~(num1 ^ num2) => ~(0100 ^ 0001) => ~(0101) => ~5 => -6-6 => 0110 => 1001 + 1 => 1010 => 10
第 6 行:
num1 = ~(num1 ^ num2) => ~(0100^ 1010) => ~(1110) => ~14 => -15-15 => 1111 => 0000 + 1 => 0001 => 1
花了一些时间,但还是交换了值。但不幸的是,它遇到了与 XOR 相同的问题,不能处理浮点数和无穷大。
试试下面的值:
function swapWithXNOR(num1,num2){ console.log(num1,num2) num1 = ~(num1^num2); num2 = ~(num1^num2); num1 = ~(num1^num2); console.log(num1,num2) } swapWithXNOR(2.3,4.5)
这是一线技巧。只需要一行代码就可以进行交换,更重要的是,无需数学运算,只需要数组的基本知识。不过它看上去可能很奇怪。
先让看看它的实际效果:
function swapWithArray(num1,num2){ console.log(num1,num2) num2 = [num1, num1 = num2][0]; console.log(num1,num2) } swapWithArray(2.3,Infinity)
在数组的下标 0 位置中存储 num1
,在下标 1 中,既将 num2
分配给 num1
,又存储了 num2
。另外,我们只是访问 [0]
,将数组中的 num1
值存储在 num2
中。而且可以在这里交换我们想要的任何东西,比如:整数、浮点数(包括无穷数)以及字符串。看上去很整洁,但是在这里失去了代码的清晰度。
这是 ES6 的功能。这是所有方法中最简单的。只需要一行代码就可以完成交换:
let num1 = 23.45; let num2 = 45.67; console.log(num1,num2); [num1,num2] = [num2,num1]; console.log(num1,num2);
这是最奇怪的一个。简单的说 IIFE 是在在定义后立即执行的函数。
可以用它来交换两个值:
function swapWithIIFE(num1,num2){ console.log(num1,num2) num1 = (function (num2){ return num2; })(num2, num2=num1) console.log(num1,num2) } swapWithIIFE(2.3,3.4)
在上面的例子中,在第4行立即调用一个函数。最后的括号是该函数的参数。第二个参数将 num1
赋值给 num2
,仅仅返回第一个参数,不过这种交换方法效率不高。
本文探讨了用于在 JavaScript 中对值进行交换的众多方法。希望对你有所帮助!
本文转载自:https://codeburst.io/10-ways-to-swap-values-in-javascript-8a1d056352dd
作者:Piyush Kochhar
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of 10 ways to exchange values in JS (share). For more information, please follow other related articles on the PHP Chinese website!