How to implement variable exchange in es6

青灯夜游
Release: 2022-04-19 16:46:56
Original
2683 people have browsed it

Variable exchange method: 1. With the help of the third variable c, the syntax "c=a;a=b;b=c;", so that the values ​​of variables a and b can be interchanged; 2. Using arrays Subscript reassignment, the syntax is "a=[a,b];b=a[0];a=a[1];"; 3. Use the destructuring assignment of the array, the syntax is "[a, b]=[b, a];".

How to implement variable exchange in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Method to implement variable exchange in es6

Method 1: With the help of the third variable

There are two variables a and b, and variable exchange can be achieved with the help of a third variable c.

  • First assign the a value to c

  • , then assign the b value to a

  • Finally assign Assign the c value to b

var a=1;
var b=2;
var c=a;
a=b;
b=c;
console.log(a,b)//2,1
Copy after login

How to implement variable exchange in es6

Method 2: Reassign the value using the array subscript

var a = 3,
    b = 4;
a = [a, b];
b = a[0];
a = a[1];
console.log(a,b)
Copy after login

How to implement variable exchange in es6

Method 3: Use the destructuring assignment of the array to exchange the value of the variable

var a = 3,
    b = 4;
[a, b] = [b, a];
console.log(a,b)
Copy after login

How to implement variable exchange in es6

[Related recommendations: javascript video Tutorialweb front-end

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

Related labels:
es6
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template