交换javascript数组中的两个项目 [英] Swapping two items in a javascript array

查看:41
本文介绍了交换javascript数组中的两个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Javascript 交换数组元素

我有一个这样的数组:

this.myArray = [0,1,2,3,4,5,6,7,8,9];

现在我想做的是,交换两个项目的位置给出它们的位置.例如,我想将第 4 项(即 3)与第 8 项(即 7)交换这应该导致:

Now what I want to do is, swap positions of two items give their positions. For example, i want to swap item 4 (which is 3) with item 8 (which is 7) Which should result in:

this.myArray = [0,1,2,7,4,5,6,3,8,9];

我怎样才能做到这一点?

How can I achieve this?

推荐答案

只需重新分配元素,创建一个中间变量来保存您覆盖的第一个变量:

Just reassign the elements, creating an intermediate variable to save the first one you over-write:

var swapArrayElements = function(arr, indexA, indexB) {
  var temp = arr[indexA];
  arr[indexA] = arr[indexB];
  arr[indexB] = temp;
};
// You would use this like: swapArrayElements(myArray, 3, 7);

如果你想让它更容易使用,你甚至可以将它添加到内置的 Array 原型中(如 kennebec@ 建议的那样);但是,请注意,这通常是一种需要避免的错误模式(因为当多个不同的库对内置类型的内容有不同的看法时,这可能会产生问题):

If you want to make this easier to use, you can even add this to the builtin Array prototype (as kennebec@ suggests); however, be aware that this is generally a bad pattern to avoid (since this can create issues when multiple different libraries have different ideas of what belongs in the builtin types):

Array.prototype.swap = function(indexA, indexB) {
   swapArrayElements(this, indexA, indexB);
};
// You would use this like myArray.swap(3, 7);

请注意,此解决方案比使用 splice() 的替代方案要高效得多.(O(1) vs O(n)).

Note that this solution is significantly more efficient than the alternative using splice(). (O(1) vs O(n)).

这篇关于交换javascript数组中的两个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆