Home  >  Article  >  Web Front-end  >  How to exchange values ​​in javascript

How to exchange values ​​in javascript

青灯夜游
青灯夜游Original
2021-06-30 14:19:422380browse

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]”.

How to exchange values ​​in javascript

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!

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