Home > Article > Web Front-end > How to exchange values in javascript
Javascript method for numerical exchange: 1. Use intermediate variables for numerical exchange, the syntax "c=a;a=b;b=c;"; 2. Use array exchange for numerical exchange, the syntax " a=[b,b=a]”.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Now there is var a = 1,b = 2;
. It is required to use javascript to exchange the values of a and b, so that a = 2,b = 1
.
1. Intermediate variables (conventional implementation)
var a = 1, b = 2; var c = a; a = b; b = c; console.log(a); // 2 console.log(b); // 1
2. Array exchange (implementation)
var a = 1, b = 2; a = [b,b = a]; console.log(a); // 2 console.log(b); // 1
【 Related recommendations: javascript learning tutorial】
The above is the detailed content of How to exchange values in javascript. For more information, please follow other related articles on the PHP Chinese website!