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

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

其他回答

这似乎还可以....

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

Flow

不是就地解决方案

let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);

让swap= (arr,i,j)=> arr.map((e,k)=> k-i ?(k-j ?E: arr[i]): arr[j]); //测试指数:3<->5 (= 'f'<->'d') 设a= ["a","b","c","d","e","f","g"]; 设b= swap(a,3,5); console.log(“\ n”,b); console.log(示例流:,交换(a, 3, 5) .reverse () . join (' - '));

就地解决方案

Let swap= (arr,i,j)=> {Let t=arr[i];arr[我]= arr [j];加勒比海盗[j] = t;返回arr} //测试指数:3<->5 (= 'f'<->'d') 设a= ["a","b","c","d","e","f","g"]; Console.log (swap(a,3,5)) console.log(示例流:,交换(a, 3, 5) .reverse () . join (' - '));

在这个解决方案中,我们使用“流模式”,这意味着swap函数返回数组作为结果-这允许轻松地继续使用dot处理。(比如reverse和join在片段中)

交换数组中两个连续的元素

array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);

如果你不想在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 ]
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");