At some point in their career, developers need to swap values. Most of the time we use the one plain old solution of “using a temporary variable”. Ugh, if only there was a better way. But wait! There is, and there’s not just one but many. In desperate times, we scour the web for solutions, find one, and copy it without ever wondering how this little snippet of code works. Lucky for you, now is the time to learn about how to swap values easily and efficiently, putting an end to your misery.
在职业生涯的某个时刻,开发人员需要交换价值。 大多数时候,我们使用一种简单的旧解决方案“使用临时变量”。 gh,如果有更好的办法。 可是等等! 有,不仅有一个,而且很多。 在绝望的时刻,我们在网上搜寻解决方案,找到解决方案,然后将其复制,而无需怀疑这小段代码是如何工作的。 幸运的是,现在该是学习如何轻松高效地交换价值,消除痛苦的时候了。
1)使用临时变量 (1) Using a temporary variable)
Let’s just get the most obvious one out of the way.
让我们让最明显的一个成为可能。
2)使用算术运算符+和- (2) Using Arithmetic Operators + and -)
Yes, you are reading correctly. We can use some mathematics magic to swap your values.
是的,您正在正确阅读。 我们可以使用一些数学魔术来交换您的价值。
Whaaat!? Yep, so let’s see how it’s working. We get the sum of both numbers on line 4. Now, if we subtract one number from the sum then we get the other number right. That’s what we are doing on line number 5. Subtracting num2 from the sum which is stored in num1 variable will give the original num1 value which we store in num2. And similarly, we get assign num2 value in num1 on line 6.
哇!? 是的,让我们看看它是如何工作的。 我们在第4行获得两个数字的总和。现在,如果从总和中减去一个数字,那么另一个数字就正确了。 这就是我们在第5行上所做的工作。从存储在num1变量中的总和中减去num2会得到我们存储在num2中的原始num1值。 同样,在第6行的num1中获得赋值num2的值。
Beware: There is also a one line swap with + and — floating around on the internet.
当心 :互联网上还存在一个带有+和-的单行交换。
Here’s how it looks:
外观如下:
The above program gives the expected result. The expression within ( ) stores num2 in num1 and then we subtract num1 — num2 which is nothing but subtracting num2 — num2 = 0. Hence, we get our result. But when we use floating-point numbers, we see some unexpected results.
上面的程序给出了预期的结果。 ()中的表达式将num2存储在num1中,然后我们减去num1 — num2,除了减去num2 — num2 = 0外什么也没有。因此,我们得到了结果。 但是,当我们使用浮点数时,会看到一些意外的结果。
Try playing with the values like below in your console.
尝试在控制台中使用如下所示的值。
3)仅使用+或-运算符 (3) Using Only + or — Operator)
We can achieve the same result just by using + operator as we did when using both + and -.
仅通过使用+运算符就可以达到与同时使用+和-相同的结果。
Let’s see it below:
让我们在下面看到它:
The above program works but sacrifices readability. On line 4, in the ( ) we are assigning num1 to num2 and the 0 next to is the return value. In short, our line 4 looks like:
上面的程序有效,但牺牲了可读性。 在()中的第4行,我们将num1分配给num2,而旁边的0是返回值。 简而言之,我们的第4行如下所示:
num2 = num1 + 0 => num2 = num1.
Hence, we get our result.
因此,我们得到了结果。
Note: Some JavaScript engines can perform their own optimizations to the above code that disregards + 0.
注意 :某些JavaScript引擎可以对上述忽略+ 0的代码执行自己的优化。
4)使用算术运算符*和/ (4) Using Arithmetic Operators * and /)
Let’s do some more magic with using * & / operators.
让我们使用*&/运算符做更多的魔术。
The principle is the same as the previous method but with some teeny tiny quirks.
其原理与先前的方法相同,但有一些微小的怪癖。
It’s the same as the previous one. We get the product of both the numbers and store them in one of the numbers. That’s what we are doing on line number 5. Then we divide one of the numbers with the product to get the first number and repeat the process to get the second number.
与上一个相同。 我们得到两个数字的乘积,并将它们存储在一个数字中。 这就是我们在第5行上执行的操作。然后,将其中一个与产品相除,得到第一个数字,然后重复此过程以获得第二个数字。
You did it! You are a “mathemagician”.
你做到了! 你是一个“ 数学家 ”。
But wait a second! What about the quirk?
但是请稍等! 那怪癖呢?
Well, let’s try this.
好吧,让我们尝试一下。
Our values are not swapped and we get a weird NaN instead. What’s that all about. If you remember your math classes, we were always told not to divide with 0 because it’s undefined. The reason lies in how limits work and some other reasons which we won’t get into. For now, let’s see other problems with this method
我们的价值观没有被交换,而是得到了一个奇怪的NaN 。 那到底是什么。 如果您还记得数学课,我们总是被告知不要除以0,因为它是不确定的。 原因在于限制的工作方式以及其他一些我们不会理解的原因。 现在,让我们看看这种方法的其他问题
Consider this example:
考虑以下示例:
Yep, it’s again NaN. Because you can’t divide anything with Infinity, it’s undefined.
是的,又是NaN 。 因为您无法使用Infinity分割任何内容,所以它是未定义的。
Want to see one more. I thought so!
想要再看一遍。 我是这么想的!
-Infinity would yield the same result as the previous example and the reason is the same as well.
-Infinity将产生与前面的示例相同的结果,原因也相同。
As it turns out even a great “mathemagician” can’t do the impossible with all his powers.
事实证明,即使是一个伟大的“ 数学家 ”也无法用他的全部能力做到不可能。
Here’s a shorter version of swapping with * and / but with the same problems:
这是用*和/交换的较短版本,但存在相同的问题:
The above code is similar to the shorter code when we were swapping using + and -. We assign num2 to num1, then our line 4 looks something like this:
当我们使用+和-进行交换时,上面的代码类似于较短的代码。 我们将num2分配给num1,然后我们的第4行看起来像这样:
num2 = num1 * num2 / num2=> num2 = num1
Voila! Our values are swapped.
瞧! 我们的价值观被交换了。
5)仅使用*或/运算符 (5) Using Only * or / Operator)
The above program works but sacrifices readability. In line 4, in the ( ) we are assigning num1 to num2 and the 1 next to is the return value. In short, our line 4 looks like:
上面的程序有效,但牺牲了可读性。 在()中的第4行中,我们将num1分配给num2,旁边的1是返回值。 简而言之,我们的第4行如下所示:
num2 = num1 * 1 => num2 = num1
Hence, we get our result.
因此,我们得到了结果。
6)使用按位异或。 (6) Using Bitwise XOR.)
XOR manipulates the binary bits. It yields 1 when we have two different inputs and 0 otherwise.
XOR操作二进制位。 当我们有两个不同的输入时,它的结果为1,否则为0。
| X | Y | X^Y| 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0
| X | Y | X ^ Y | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0
So, let’s understand how it works!
因此,让我们了解其工作原理!
4-bit binary of 10 -> 1010
4位二进制数10-> 1010
4-bit binary of 1 -> 0001
1-> 0001的4位二进制
Now,
现在,
On line 5: num1 = num1 ^ num2 => 1010 ^ 0001 => 1011 => 7 On line 6: num2 = num1 ^ num2 => 1011 ^ 0001 => 1010 => 10On line 7: num1 = num1 ^ num2 => 1011 ^ 1010 => 0001 => 1
Voila! And we have our swapped values.
瞧! 我们有交换的值。
Let’s see another example.
让我们来看另一个例子。
Umm! Where are the swapped values? We just get the integer part of the number. And that’s the problem right there. The XOR assumes that the input is an integer and hence performs the calculations accordingly. But the floating-point number are not integers and are represented by IEEE 754 standard, which breaks the numbers in three parts: a sign bit, a group of bits representing an exponent, and another group representing a number between 1 (inclusive) and 2 (exclusive), the mantissa. Hence we get incorrect values.
嗯! 交换的值在哪里? 我们只是得到数字的整数部分。 这就是那里的问题。 XOR假定输入是整数,因此将相应地执行计算。 但是浮点数不是整数,而是由IEEE 754标准表示,它将数字分为三部分: 符号位,一组代表指数的位和另一组代表1(含)和2之间的数字(不包括), 尾数。 因此,我们得到不正确的值。
Another example:
另一个例子:
Again. We don’t see the expected result. That’s because both Infinity and –Infinity are both floating-point numbers. And as we discussed above, floating-point numbers are a problem for XOR.
再次。 我们没有看到预期的结果。 这是因为Infinity和–Infinity都是浮点数。 正如我们上面所讨论的,对于XOR,浮点数是一个问题。
7)使用按位XNOR。 (7) Using Bitwise XNOR.)
It manipulates the binary bits as well and is the opposite of XOR. XNOR yields 0 when we have two different inputs and 1 otherwise. JavaScript doesn’t have a single operator that performs XNOR, so we use the NOT operator to negate the result of XOR.
它也操纵二进制位,这与XOR相反。 当我们有两个不同的输入时,XNOR产生0,否则产生1。 JavaScript没有执行XNOR的单个运算符,因此我们使用NOT运算符来取反XOR的结果。
| X | Y | XNOR | 1 | 1 | 1| 1 | 0 | 0| 0 | 1 | 0| 0 | 0 | 1
| X | Y | XNOR | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1个
So, let’s understand how it works!
因此,让我们了解其工作原理!
4-bit binary of 10 -> 1010
4位二进制数10-> 1010
4-bit binary of 1 -> 0001
1-> 0001的4位二进制
On line 4:
在第4行:
num1 = ~(num1 ^ num2) => ~(1010 ^ 0001) =>~(1011) => ~11 => -12
Since we have a negative number, we need to convert it back to binary & perform 2’s complement to get back the decimal value like:
由于我们有一个负数,我们需要将其转换回二进制并执行2的补码以获取十进制值,例如:
-12 => 1100 => 0011 + 1 => 0100
On line 5:
在第5行:
num2 = ~(num1 ^ num2) => ~(0100 ^ 0001) => ~(0101) => ~5 => -6-6 => 0110 => 1001 + 1 => 1010 => 10
On line 6:
在第6行:
num1 = ~(num1 ^ num2) => ~(0100^ 1010) => ~(1110) => ~14 => -15-15 => 1111 => 0000 + 1 => 0001 => 1
That took some time but we have our swapped values. But unfortunately, it’s plagued with the same problems as XOR. It can’t deal with floating-point numbers and infinities.
花费了一些时间,但我们交换了价值。 但不幸的是,它遇到了与XOR相同的问题。 它不能处理浮点数和无穷大。
Try to experiment with some values like below
尝试尝试如下所示的一些值
8)在数组中使用分配 (8) Using assignment within Array)
It’s a one-line trick. Really! You only need a line to perform swapping and more importantly no math. You just need a basic knowledge of arrays. It may look weird but hold on tight.
这是一个单行的把戏。 真! 您只需要一行即可执行交换,更重要的是,无需数学运算。 您只需要数组的基本知识。 它可能看起来很奇怪,但请紧紧抓住。
So, let’s see it in action!
所以,让我们看看它的实际效果!
In the index 0 of the array we are storing num1, and in index 1 we are both assigning num2 to num1 and storing num2 as well. Also, we are just accessing [0] to store the num1 value from array in num2. And we can swap anything we want here integers, floating points including infinities as well as strings. It’s quite neat actually but we lose code clarity here. Let’s explore something else.
在数组的索引0中,我们存储num1,在索引1中,我们既将num2分配给num1,又存储了num2。 另外,我们只是访问[0],将数组中的num1值存储在num2中。 而且我们可以在这里交换我们想要的任何东西,整数,浮点数(包括无穷数)以及字符串。 实际上这很整洁,但是我们在这里失去了代码的清晰度。 让我们探索其他东西。
9)使用解构表达式 (9) Using Destructuring Expression)
It is an ES6 feature. And it’s the simplest of them all. In a single line, we can swap values like:
这是ES6的功能。 这是所有人中最简单的。 在一行中,我们可以交换以下值:
10)使用立即调用的函数表达式(IIFE) (10) Using Immediately Invoked Function Expression (IIFE))
Here’s a weird one. An IIFE is in short, a function that just executes immediately after it is defined.
这是一个奇怪的。 简而言之,IIFE是在定义后立即执行的功能。
Here’s how we can use it to swap values:
我们可以使用它来交换值:
In the above example, we are immediately invoking a function on line 4. The parenthesis at the end are the arguments to the function. The second argument assigns num1 to num2 and the first argument, num1 is just returned. Hence, the values are swapped. Just keep in mind that this method of swapping is not efficient.
在上面的示例中,我们立即在第4行调用一个函数。最后的括号是该函数的参数。 第二个参数将num1分配给num2,第一个参数num1刚刚返回。 因此,将交换值。 请记住,这种交换方法效率不高。
结论 (Conclusion)
This article dove into a number of options you have for swapping values in JavaScript. Hopefully, you find this information helpful, feel free to leave a comment with your thoughts. Thanks for reading!
本文探讨了用于交换JavaScript中的值的许多选项。 希望您发现此信息对您有所帮助,请随时发表您的想法。 谢谢阅读!
翻译自: JavaScript/