将数组元素从一个数组位置移动到另一个数组位置。我很难弄清楚如何移动数组元素。例如,考虑到以下情况:var arr = [ 'a', 'b', 'c', 'd', 'e'];我如何写一个函数来移动'd'以前'b'?或'a'后'c'?移动后,应更新其余元素的索引。这意味着在移动arr后的第一个例子中,arr[0]将=‘a’,arr[1]=‘d’arr[2]=‘b’,arr[3]=‘c’,arr[4]=‘e’。这看起来应该很简单,但是我不能把我的头绕在这上面。
3 回答

倚天杖
TA贡献1828条经验 获得超3个赞
Array.prototype.move = function(from, to) { this.splice(to, 0, this.splice(from, 1)[0]);};
Array.prototype.move2 = function(pos1, pos2) { // local variables var i, tmp; // cast input parameters to integers pos1 = parseInt(pos1, 10); pos2 = parseInt(pos2, 10); // if positions are different and inside array if (pos1 !== pos2 && 0 <= pos1 && pos1 <= this.length && 0 <= pos2 && pos2 <= this.length) { // save element from position 1 tmp = this[pos1]; // move element down and shift other elements up if (pos1 < pos2) { for (i = pos1; i < pos2; i++) { this[i] = this[i + 1]; } } // move element up and shift other elements down else { for (i = pos1; i > pos2; i--) { this[i] = this[i - 1]; } } // put element from position 1 to destination this[pos2] = tmp; } }
添加回答
举报
0/150
提交
取消