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

小云云
Release: 2018-02-05 09:31:40
Original
1536 people have browsed it

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;
Copy after login

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;
Copy after login

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];
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!