是否有更简单的方法来交换数组中的两个元素?

var a = list[x], b = list[y];
list[y] = a;
list[x] = b;

当前回答

var a = [1,2,3,4,5], b=a.length;

for (var i=0; i<b; i++) {
    a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];

其他回答

如果你想要一个单一的表达式,使用本地javascript, 记住,拼接操作的返回值 包含已删除的元素。

var 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"

编辑:

当array. splice()返回一个数组时,表达式末尾的[0]是必要的,在这种情况下,我们需要返回数组中的单个元素。

对于数值,可以使用按位的异或来避免临时变量

list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];

或算术和(注意,这仅适用于x + y小于数据类型的最大值时)

list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];

为了简洁起见,这里有一个丑陋的一行代码版本,它只比上面所有的连接和切片稍微好看一点。公认的答案才是正确的选择,而且可读性更强。

考虑到:

var foo = [ 0, 1, 2, 3, 4, 5, 6 ];

如果你想交换两个下标(a和b)的值;这样就可以了:

foo.splice( a, 1, foo.splice(b,1,foo[a])[0] );

例如,如果你想交换3和5,你可以这样做:

foo.splice( 3, 1, foo.splice(5,1,foo[3])[0] );

or

foo.splice( 5, 1, foo.splice(3,1,foo[5])[0] );

两者都产生了相同的结果:

console.log( foo );
// => [ 0, 1, 2, 5, 4, 3, 6 ]

#splicehatersarepunks:)

可以通过以下方式交换数组中的元素:

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]

这是一个精简版 arr中i1和i2的值互换

arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))