Javascript 交换javascript数组中的两个项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4011629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:08:15  来源:igfitidea点击:

Swapping two items in a javascript array

javascriptarrays

提问by ssdesign

Possible Duplicate:
Javascript swap array elements

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

I have a array like this:

我有一个这样的数组:

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

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:

现在我想做的是,交换两个项目的位置给出它们的位置。例如,我想将第 4 项(即 3)与第 8 项(即 7)交换,结果如下:

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

How can I achieve this?

我怎样才能做到这一点?

回答by kennebec

The return value from a splice is the element(s) that was removed-

拼接的返回值是被移除的元素——

no need of a temp variable

不需要临时变量

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

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

alert(arr.swapItems(3, 7));

returned value: (Array)

返回值:(数组)

    0,1,2,7,4,5,6,3,8,9

回答by Michael Aaron Safyan

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

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 原型中(如 kennebec@ 建议的那样);但是,请注意,这通常是一种需要避免的错误模式(因为当多个不同的库对内置类型的内容有不同的看法时,这可能会产生问题):

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

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

请注意,此解决方案比使用 splice() 的替代方案更有效。(O(1)与O(n))。

回答by Nick Craver

You can just use a temp variable to move things around, for example:

您可以只使用临时变量来移动事物,例如:

var temp = this.myArray[3];
this.myArray[3] = this.myArray[7];
this.myArray[7] = temp;

You can test it out here, or in function form:

您可以在此处或以函数形式对其进行测试

Array.prototype.swap = function(a, b) {
  var temp = this[a];
  this[a] = this[b];
  this[b] = temp;
};

Then you'd just call it like this:

然后你就可以这样称呼它:

this.myArray.swap(3, 7);

You can test that version here.

您可以在此处测试该版本