在JavaScript阵列交换两个项目 [英] Swapping two items in a javascript array
问题描述
可能重复:结果
的Javascript交换数组元素
我有一个这样的数组:
this.myArray = [0,1,2,3,4,5,6,7,8,9];
现在我想要做的是,两个项目交换位置给自己的立场。
例如,我要与第8项(也就是7)交换项目4(也就是3)
这将导致:
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);
如果你想使这个更容易使用,你甚至可以将其添加到内置阵列原型(如肯纳贝克@建议);但是,要知道,这通常是一个坏的模式,以避免(因为这可以创建问题,当多个不同的图书馆有在内建类型属于什么不同的想法):
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);
请注意,该溶液显著比使用替代剪接更有效()。 (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屋!