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

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

当前回答

只是为了好玩,另一种不使用任何额外变量的方法是:

Var arr = [1,2,3,4,5,6,7,8,9]; //交换索引0和2 arr (arr)。长度]= arr[0];//将idx1复制到数组的末尾 Arr [0] = Arr [2];//复制idx2到idx1 Arr [2] = Arr [Arr .length-1];//复制idx1到idx2 arr.length——;//删除idx1(被添加到数组的末尾) Console.log (arr);// -> [3,2,1,4,5,6,7,8,9]

其他回答

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

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;
}

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

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

摘要:http://www.greywyvern.com/?post=265

var a = 5, b = 9;    
b = (a += b -= a) - b;    
alert([a, b]); // alerts "9, 5"

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

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

你可以交换任意数量的对象或文字,甚至是不同类型的对象或文字,使用一个简单的恒等函数,如下所示:

var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);

针对你的问题:

var swap = function (x){return x};
list[y]  = swap(list[x], list[x]=list[y]);

这在JavaScript中是可行的,因为它接受额外的参数,即使它们没有声明或使用。赋值a=b等,发生在a被传递到函数之后。