Home  >  Article  >  Web Front-end  >  10 ways to exchange values ​​in JS (share)

10 ways to exchange values ​​in JS (share)

青灯夜游
青灯夜游forward
2021-01-07 18:36:192694browse

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.

1. Use temporary variables

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)

2. Use arithmetic operators and -

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)

3. Just use the or- operator

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.

4. Use arithmetic operators * and /

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.

5. Only use the * or / operator

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.

6. Use bitwise exclusive OR (XOR).

XOR is used to perform binary bit operations. Its result is 1 when there are two different inputs and 0 otherwise.

##XYX^Y1 10101011000

先了解其工作原理!

function swapWithXOR(num1,num2){
  console.log(num1,num2)

  num1 = num1^num2;
  num2 = num1^num2; 
  num1 = num1^num2;

  console.log(num1,num2)
}
// 试试负值会怎样
swapWithXOR(10,1)

10 的4 位二进制数 -> 1010

1 的 4 位二进制数 -> 0001

现在:

第四行: 
num1 = num1 ^ num2 
    => 1010 ^ 0001 
    => 1011 
    => 7 
第五行: 
num2 = num1 ^ num2 
    => 1011 ^ 0001 
    => 1010 
    => 10
第六行: 
num1 = num1 ^ num2 
    => 1011 ^ 1010 
    => 0001 
    => 1

两个值交换了。

再来看另一个例子:

function swapWithXOR(num1,num2){
  console.log(num1,num2)

  num1 = num1^num2;
  num2 = num1^num2;
  num1 = num1^num2;

  console.log(num1,num2)
}

swapWithXOR(2.34,3.45)

嗯??交换的值在哪儿?我们只是得到了数字的整数部分,这就是问题所在。 XOR 假定输入是整数,所以···相应地执行计算。但是浮点数不是整数,而是由 IEEE 754 标准表示的,将数字分为三部分:符号位、代表指数的一组位和代表尾数的一组位。位数是介于1(含)和2(不含)之间的数字。所以得到的值不正确。

另一个例子:

function swapWithXOR(num1,num2){
  console.log(num1,num2)

  num1 = num1^num2;
  num2 = num1^num2;
  num1 = num1^num2;

  console.log(num1,num2)
}
// 试试 infinities 和整数值.
swapWithXOR(-Infinity,Infinity)

毫无意外,我们没有得到预期的结果。这是因为 Infinity– Infinity 都是浮点数。正如我们在前面所讨论的,对于 XOR,浮点数是一个问题。

7、使用按位同或 (XNOR)

它用来进行二进制位运算,但是与 XOR 正好相反。当有两个不同的输入时,XNOR 的结果是 0,否则结果为 1。 JavaScript 没有执行 XNOR 的运算符,所以要用 NOT 运算符对 XOR 的结果求反。

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)

8、在数组中进行赋值

这是一线技巧。只需要一行代码就可以进行交换,更重要的是,无需数学运算,只需要数组的基本知识。不过它看上去可能很奇怪。

先让看看它的实际效果:

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 中。而且可以在这里交换我们想要的任何东西,比如:整数、浮点数(包括无穷数)以及字符串。看上去很整洁,但是在这里失去了代码的清晰度。

9、使用解构表达式

这是 ES6 的功能。这是所有方法中最简单的。只需要一行代码就可以完成交换:

let num1 = 23.45;
let num2 = 45.67;

console.log(num1,num2);

[num1,num2] = [num2,num1];

console.log(num1,num2);

10、使用立即调用的函数表达式(IIFE)

这是最奇怪的一个。简单的说 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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete