我很難弄清楚如何移動數組元素。 例如,給出如下內容: html
var arr = [ 'a', 'b', 'c', 'd', 'e'];
我爲何能寫入移動功能'd'
以前, 'b'
? 數組
或'a'
後'c'
? app
移動以後,應更新其他元素的索引。 這意味着在第一個示例中,移動後arr [0] ='a',arr [1] ='d'arr [2] ='b',arr [3] ='c',arr [4] = 'e' jsp
這看起來應該很簡單,可是我沒法將其包裹住。 函數
您能夠實現一些基本的微積分,並建立通用函數以將數組元素從一個位置移動到另外一位置。 this
對於JavaScript,它看起來像這樣: spa
function magicFunction (targetArray, indexFrom, indexTo) { targetElement = targetArray[indexFrom]; magicIncrement = (indexTo - indexFrom) / Math.abs (indexTo - indexFrom); for (Element = indexFrom; Element != indexTo; Element += magicIncrement){ targetArray[Element] = targetArray[Element + magicIncrement]; } targetArray[indexTo] = targetElement; }
請查看「積木」中的「移動數組元素」以獲取詳細說明。 prototype
http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html code
在數組中移動元素,返回包含已移動元素的數組。 htm
array.move(index, howMany, toIndex);
index :元素移動的索引。 若是爲負, 索引將從末尾開始。
howMany :要從索引移動的元素數。
toIndex :放置移動元素的數組的索引。 若是爲負,則toIndex將從結尾開始。
array = ["a", "b", "c", "d", "e", "f", "g"]; array.move(3, 2, 1); // returns ["d","e"] array; // returns ["a", "d", "e", "b", "c", "f", "g"]
Array.prototype.move || Object.defineProperty(Array.prototype, "move", { value: function (index, howMany, toIndex) { var array = this, index = parseInt(index) || 0, index = index < 0 ? array.length + index : index, toIndex = parseInt(toIndex) || 0, toIndex = toIndex < 0 ? array.length + toIndex : toIndex, toIndex = toIndex <= index ? toIndex : toIndex <= index + howMany ? index : toIndex - howMany, moved; array.splice.apply(array, [toIndex, 0].concat(moved = array.splice(index, howMany))); return moved; } });
最後,我將這兩種方法結合起來,不管在長距離仍是短距離移動時,效果都更好。 我獲得了至關一致的結果,可是這可能會被比我聰明的人進行一些調整,以針對不一樣的尺寸進行不一樣的工做,等等。
當移動物體較小距離時,使用其餘一些方法比使用拼接要快得多(x10)。 可是,這可能會根據數組的長度而變化,可是對於大型數組而言確實如此。
function ArrayMove(array, from, to) { if ( Math.abs(from - to) > 60) { array.splice(to, 0, array.splice(from, 1)[0]); } else { // works better when we are not moving things very far var target = array[from]; var inc = (to - from) / Math.abs(to - from); var current = from; for (; current != to; current += inc) { array[current] = array[current + inc]; } array[to] = target; } }
http://jsperf.com/arraymove-many-sizes
splice()方法在數組中添加/刪除項目,並返回刪除的項目。
注意:此方法更改原始數組。 / w3schools /
Array.prototype.move = function(from,to){ this.splice(to,0,this.splice(from,1)[0]); return this; }; var arr = [ 'a', 'b', 'c', 'd', 'e']; arr.move(3,1);//["a", "d", "b", "c", "e"] var arr = [ 'a', 'b', 'c', 'd', 'e']; arr.move(0,2);//["b", "c", "a", "d", "e"]
因爲該函數是可連接的,所以也能夠工做:
alert(arr.move(0,2).join(','));
個人2c。 易於閱讀,有效,快速,不會建立新數組。
function move(array, from, to) { if( to === from ) return array; var target = array[from]; var increment = to < from ? -1 : 1; for(var k = from; k != to; k += increment){ array[k] = array[k + increment]; } array[to] = target; return array; }