如何在 JavaScript 中交换两个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16201656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to swap two variables in JavaScript
提问by Lukas
I have this two variables:
我有这两个变量:
var a = 1,
b = 2;
My question is how to swap them? Only this variables, not any objects.
我的问题是如何交换它们?只有这个变量,没有任何对象。
回答by showdev
Here's a one-liner to swap the values of two variables.
Given variables a
and b
:
这是一个用于交换两个变量值的单行程序。
给定变量a
和b
:
b = [a, a = b][0];
Demonstration below:
演示如下:
var a=1,
b=2,
output=document.getElementById('output');
output.innerHTML="<p>Original: "+a+", "+b+"</p>";
b = [a, a = b][0];
output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";
<div id="output"></div>
回答by Pedro Justo
ES6 (Firefox and Chrome already support it (Destructuring Assignment Array Matching)):
ES6(Firefox 和 Chrome 已经支持(解构赋值数组匹配)):
let a = 5, b = 6;
[a, b] = [b, a];
console.log(`${a} ${b}`);
回答by Ted Hopp
You can do this:
你可以这样做:
var a = 1,
b = 2,
tmp;
tmp = a;
a = b;
b = tmp;
For readability and maintainability, this can't be beat (at least in JavaScript). Anybody maintaining the code (including you six months from now) will know exactly what's going on.
对于可读性和可维护性,这是无可匹敌的(至少在 JavaScript 中)。任何维护代码的人(包括六个月后的您)都会确切地知道发生了什么。
Since these are integers, you can also use any number of clever tricks1to swap without using a third variable. For instance you can use the bitwise xor operator:
由于这些是整数,您还可以使用任意数量的巧妙技巧1进行交换,而无需使用第三个变量。例如,您可以使用按位异或运算符:
let a = 1, b = 2;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log('a is now:', a);
console.log('b is now:', b);
This is called the XOR swap algorithm. Its theory of operation is described in this Wikipedia article.
这称为 XOR 交换算法。它的操作理论在这篇维基百科文章中有所描述。
1"The competent programmer is fully aware of the limited size of his own skull. He therefore approaches his task with full humility, and avoids clever tricks like the plague."— Edsger W. Dijkstra
1 “称职的程序员完全意识到自己头骨的有限大小。因此,他以完全谦逊的态度对待自己的任务,并避免像瘟疫一样聪明的把戏。” — Edsger W. Dijkstra
回答by Ruben Verborgh
Don't use the code below. It is notthe recommended way to swap the values of two variables (simply use a temporary variablefor that). It just shows a JavaScript trick.
不要使用下面的代码。这不是交换两个变量值的推荐方法(只需为此使用临时变量)。它只是展示了一个 JavaScript 技巧。
This solution uses no temporary variables, no arrays, only one addition, and it's fast.
In fact, it is sometimes faster than a temporary variable on several platforms.
It works for all numbers, never overflows, and handles edge-cases such as Infinity and NaN.
这个解决方案不使用临时变量,不使用数组,只添加一个,而且速度很快。事实上,它有时比多个平台上的临时变量更快。
它适用于所有数字,从不溢出,并处理诸如 Infinity 和 NaN 之类的边缘情况。
a = b + (b=a, 0)
It works in two steps:
它分两步工作:
(b=a, 0)
setsb
to the old value ofa
and yields0
a = b + 0
setsa
to the old value ofb
(b=a, 0)
设置b
为旧值a
并产生0
a = b + 0
设置a
为旧值b
回答by Peter
Since ES6, you can also swap variables more elegantly:
从 ES6 开始,您还可以更优雅地交换变量:
var a = 1,
b = 2;
[a, b] = [b, a];
console.log('a:', a, 'b:', b); // a: 2 b: 1
回答by bobobobo
Here's a one-liner, assuming a
and b
exist already and have values needing to be swapped:
这是一个单行,假设a
并且b
已经存在并且需要交换值:
var c=a, a=b, b=c;
As @Kay mentioned, this actually performs betterthan the array way (almost 2x as fast).
正如@Kay 所提到的,这实际上比数组方式表现得更好(几乎快 2倍)。
回答by mehulmpt
You can now finally do:
你现在终于可以做:
var a = 5;
var b = 10;
[a, b] = [b, a]; // ES6
console.log(a, b);
回答by Nope
回答by Jalak Patoliya
ES6+ method: Since ES6, you can swap variables more elegantly. You can use destructuring assignment array matching. It's simply. var a=10 b=20;
ES6+ 方法:从 ES6 开始,你可以更优雅地交换变量。您可以使用解构赋值数组匹配。很简单。var a=10 b=20;
[a, b] = [b, a]
[a, b] = [b, a]
console.log(a,b) // 20 10
console.log(a,b) // 20 10
回答by DmiN
You could use a temporary swap variable or XOR.
您可以使用临时交换变量或 XOR。
a = a ^ b
b = a ^ b
a = a ^ b
This is just a basic logical concept and works in every language that supports XOR operation.
这只是一个基本的逻辑概念,适用于所有支持 XOR 运算的语言。
edit:see the Comments. Forgot to tell that this works for sure only with integer. Assumed the integer variables from question's thread
编辑:见评论。忘了说这肯定只适用于整数。假设来自问题线程的整数变量