Home  >  Article  >  Web Front-end  >  How to implement the exchange method of two variable values ​​​​in JS

How to implement the exchange method of two variable values ​​​​in JS

亚连
亚连Original
2018-06-07 17:38:533375browse

This article mainly introduces how to realize that two variables are worth exchanging without the intermediate variable temp in JS. Friends in need can refer to it

1. Use addition and subtraction;

var a=1;
var b=2;
a=a+b;
b=a-b;
a=a-b;

2. Use multiplication and division (multiplication and division are more like the mapping of addition and subtraction to multiplication and division operations)

var a=1;
var b=2;
 a = a * b;
 b = a / b;
 a = a / b;

Note: This method can exchange integers and floating point Type numeric variables, but there may be a loss of precision when dealing with floating point types, and b cannot be 0 when multiplying and dividing;

3. Flexibility of using arrays

var a=1;
var b=2;
a=[b,b=a][0];

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Use selenium to capture Taobao data information

##How to use Baidu Map to implement map grid

Comparison and distinction between Express and Koa2 in nodejs (detailed tutorial)

The above is the detailed content of How to implement the exchange method of two variable values ​​​​in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn