Home  >  Article  >  Web Front-end  >  JS does not use the intermediate variable temp to realize that two variables are worthy of exchange implementation code

JS does not use the intermediate variable temp to realize that two variables are worthy of exchange implementation code

小云云
小云云Original
2018-02-05 09:31:401556browse

This article mainly introduces to you how to realize the exchange of two variables without using the intermediate variable temp in JS. Friends who need it can refer to it. I hope it can help everyone.

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 variables with integer and floating-point values, but when dealing with floating-point There may be a loss of precision when using point types, and b cannot be 0 during multiplication and division;

3. Flexibility of using arrays


##

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

Related recommendations:


Introduction to the method of realizing shared variable values ​​​​in WeChat applet

How to exchange two variable values ​​​​in PHP ( No third variable is used)

Seven solutions for exchanging the values ​​​​of two variables in JavaScript

The above is the detailed content of JS does not use the intermediate variable temp to realize that two variables are worthy of exchange implementation code. 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