我有一个对象数组,我想交换数组中两个元素的位置。
我试过这个:
var tempObject = array.splice(index, 1, array[index + 1]);
array.splice(index+1, 1, tempObject);
但它似乎无法正常工作,因为它会导致一些奇怪的错误。例如,我无法使用对象的方法。调用 array[x].getName
会导致错误。
任何人都可以在这里伸出援助之手吗?
为了以防万一,我使用了 object.prototype
添加方法。
您代码中的错误是 splice 返回项目数组,而不是单个项目。由于您正在提取单个项目,因此您可以:
var tempObject = array.splice(index, 1, array[index + 1])[0]; // get the item from the array
array.splice(index+1, 1, tempObject);
This answer提供了一个较短的版本,也使用拼接:
array[index] = array.splice(index+1, 1, array[index])[0];
Another very interesting answer既短又fast :
function identity(x){return x};
array[index] = identity(array[index+1], array[index+1]=array[index]);