Exchange the value of two variables, without the help of the third variable three methods (JS implementation)

Source: Internet
Author: User

The first type: arithmetic Operation method

Its principle is: The A, b as a point on the axis, around the distance between two points to calculate.
The specific process: the first sentence "a=b-a" to find the distance ab two points, and save it in a, the second sentence "b=b-a" to find a to the origin of the distance (b to the origin of the distance and the difference between AB two points), and save it in B; the third sentence "A=b+a" Find the distance from the B to the origin (the sum of the distance from a to the origin of the AB two point) and save it in a. Complete the interchange.

Effect:

The second type: with an array

The principle does not need to say much, with the help of array subscript and operator priority implementation

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

Effect:

The third type: bitwise arithmetic

Principle:

The ^ operator is similar to |, but a little different is that if two operation bits are 1, the result is 0.

1 binary representation is 0 0 0 0 0 0 1

3 binary representation is 0 0 0 0 0 1 1

So the result of 1 ^ 3 is 2

Effect:

Exchange the value of two variables, without the help of the third variable three methods (JS implementation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.