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

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

当前回答

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

考虑到:

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:)

其他回答

如果你不想在ES5中使用临时变量,这是交换数组元素的一种方法。

var swapArrayElements = function (a, x, y) {
  if (a.length === 1) return a;
  a.splice(y, 1, a.splice(x, 1, a[y])[0]);
  return a;
};

swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]

好吧,你不需要缓冲两个值-只有一个:

var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
function moveElement(array, sourceIndex, destinationIndex) {
    return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];

moveElement(arr, "2","4");

这似乎还可以....

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的干净方法。

当这个问题被问到时,它并不存在,但是ES2015引入了数组解构,允许你这样写:

let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1