有没有一种更简单的方法来交换数组中的两个元素?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
a = [b, b = a][0]
,正如@Jan所指出的那样。尽管如此,我仍然倾向于使用临时变量的方法,因为它是跨语言(例如C/C++)并且通常是我首先想到的方法。 - Ultimater[list[y],list[x]] = [list[x],list[y]];
- protoEvangelion[arr[1], arr[0]]
会改变原始数组吗?这对我来说看起来难以理解。 - jajabarrvar A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x] = A.splice(y, 1, A[x])[0];
alert(A); // Alerts "2,1,3,4,5,6,7,8,9"
在表达式末尾需要 [0]
,因为 Array.splice()
返回一个数组,在这种情况下我们需要返回数组中的单个元素。
[A[x]] = A.splice(y, 1, A[x])
! - Mister Jojo[ list[x], list[y] ] = [ list[y], list[x] ];
这看起来还不错....
var b = list[y];
list[y] = list[x];
list[x] = b;
然而,使用
var b = list[y];
意味着在作用域的其余部分将会存在一个 b 变量。这可能会导致内存泄漏。虽然不太可能,但最好还是避免。
把这个放到 Array.prototype.swap 里可能是一个不错的主意。
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
可以这样调用:
list.swap( x, y )
这是一种干净的方法,既可以避免内存泄漏,又可以遵循DRY原则。
Array.prototype.swap = function (x,y) { if (x >= 0 && x < this.length && y >= 0 && y < this.length) { var b = this[x]; this[x] = this[y]; this[y] = b; } return this; };
- David R.嗯,你不需要缓存两个值 - 只需要一个:
var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
您可以按照以下方式交换数组中的元素:
list[x] = [list[y],list[y]=list[x]][0]
请看以下例子:
list = [1,2,3,4,5]
list[1] = [list[3],list[3]=list[1]][0]
//list is now [1,4,3,2,5]
请注意:对于普通变量,它的工作方式相同。var a=1,b=5;
a = [b,b=a][0]
[list[x],list[y]] = [list[y],list[x]];
。 - Claudiathis[0] > this[1] && (this[0] = [this[1],this[1]=this[0]][0]);
,那么这是一种美丽的交换模式。 - Redu考虑一种不需要定义第三个变量的解决方案:
function swap(arr, from, to) {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}
var letters = ["a", "b", "c", "d", "e", "f"];
swap(letters, 1, 4);
console.log(letters); // ["a", "e", "c", "d", "b", "f"]
注意:您可能需要添加其他检查,例如检查数组长度。该解决方案是可变的,因此swap
函数无需返回新数组,它只是对传入的数组进行修改。
arr.splice(from, 1, arr.splice(to, 1, ...arr[from]))
。 - Orkun Tuzel通过使用按位异或(bitwise XOR),您可以避免使用临时变量来处理数值:
list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];
list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];
list[y] = list[x] - list[x];
不就是等同于 list[y] = 0;
吗? - ErikEarray.splice(IndexToSwap, 2, array[IndexToSwap + 1], array[IndexToSwap]);
with()
可以在一行中完成:list.with(x,list[y]).with(y,list[x])
看看我的答案和示例! - XMehdi01with()
可以在一行中完成:list.with(x,list[y]).with(y,list[x])
看看我的回答,附带一个示例! - undefined