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

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

当前回答

下面是一个变体,它首先检查数组中是否存在索引:

Array.prototype.swapItems = function(a, b){
    if(  !(a in this) || !(b in this) )
        return this;
    this[a] = this.splice(b, 1, this[a])[0];
    return this;
}

如果索引不存在,它目前只会返回这个,但是您可以很容易地修改失败时的行为

其他回答

这似乎还可以....

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

使用ES6可以这样做…

假设你有这两个数组……

const a = ["a", "b", "c", "d", "e"];
const b = [5, 4, 3, 2, 1];

你想交换第一个值:

const [a0] = a;
a[0] = b[0];
b[0] = a0;

和值:

a; //[5, "b", "c", "d", "e"]
b; //["a", 4, 3, 2, 1]

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在片段中)

如果你想要一个单一的表达式,使用本地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]是必要的,在这种情况下,我们需要返回数组中的单个元素。

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");