2010-10-25 89 views
31

可能重複:
Javascript swap array elements交換兩個項目在JavaScript陣列

我有一個這樣的數組:

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

現在我想做的是,兩個項目的交換位置給他們的位置。 例如,我要與項目8(也就是7) 應該結果是在交換項目4(也就是3):

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

我怎樣才能做到這一點?

+2

重複(與一些離譜的解決方案爲您的娛樂) - http://stackoverflow.com/questions/872310/javascript-swap-array-elements – 2010-10-25 03:01:52

回答

50

只是重新分配的元素,創造了一箇中間變量,以節省您在寫第一個:

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

如果你想使這個更容易使用,你甚至可以將其添加到內置陣列原型(如kennebec @建議);但是,請注意,這通常是一個糟糕的模式,以避免(因爲這可能引起問題,當多個不同的庫具有的內建的類型屬於什麼不同的想法):

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

請注意,此解決方案是顯著更有效比使用splice()的替代方法要好。 (O(1)對O(n))。

+9

O(1)下面不是 – Nick 2014-04-05 18:34:49

5

您可以只使用一個臨時變量左右移動的東西,例如:

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

You can test it out here,或以函數形式:

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

然後你只需要調用它像這樣:

this.myArray.swap(3, 7); 

You can test that version here

75

從剪接的返回值是一個爲被切除,

不需要的臨時變量的元件(一個或多個)

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

返回值:(陣列)

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

尼斯!怎麼沒有人投票答覆這個答案。 – zachzurn 2011-11-22 08:02:28

+0

理解該解決方案的關鍵是splice()可以在啓動後具有其他項目,deleteCount將在拼接位置插入。只有一個缺陷:splice()返回一個數組,所以要從該數組中獲得一個(也是唯一的)元素,就必須說:'this [a] = this.splice(b,1,this [a]) [0];' – trembl 2011-12-08 07:11:10

+13

考慮到這一點,splice是O(n),http://stackoverflow.com/questions/11514308/big-o-of-javascript-arrays – Nick 2014-04-05 18:33:51