交换对象数组中的元素

Jam*_*ham 1 javascript arrays swap object

我有一个对象数组,我想交换数组中两个元素的位置.我试过这个:

var tempObject = array.splice(index, 1, array[index + 1]);
array.splice(index+1, 1, tempObject);
Run Code Online (Sandbox Code Playgroud)

但它似乎没有正常工作,因为它会导致一些奇怪的错误.例如,我无法使用该对象的方法.调用会array[x].getName导致错误.

任何身体都可以在这里伸出援助之手吗?

为了防止它变得很重要,我已经习惯object.prototype了添加方法.

Tib*_*bos 6

代码中的错误是splice返回一个项目数组,而不是单个项目.由于您要提取单个项目,因此可以执行以下操作:

var tempObject = array.splice(index, 1, array[index + 1])[0]; // get the item from the array
array.splice(index+1, 1, tempObject);
Run Code Online (Sandbox Code Playgroud)

这个答案提供了一个更短的版本,也使用拼接:

array[index] = array.splice(index+1, 1, array[index])[0];
Run Code Online (Sandbox Code Playgroud)

另一个非常有趣的答案是短而:

function identity(x){return x};

array[index] = identity(array[index+1], array[index+1]=array[index]);
Run Code Online (Sandbox Code Playgroud)