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

How to exchange values ​​in javascript

青灯夜游
Release: 2023-01-07 11:41:25
Original
2452 people have browsed it

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

2. Array exchange (implementation)

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

【 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!

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