语法为Array.splice https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice is:
yourArray.splice(index, howmany, element1, /*.....,*/ elementX);
Where:
-
index是数组中要开始删除元素的位置
-
howmany是你想要从中删除多少个元素index
-
元素1,...,元素X是您想要从位置插入的元素index.
这意味着splice()
可用于删除元素、添加元素或替换数组中的元素,具体取决于您传递的参数。
请注意,它返回已删除元素的数组。
一些不错且通用的东西是:
Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
然后只需使用:
var ar = [1,2,3,4,5];
ar.move(0,3);
alert(ar) // 2,3,4,1,5
Diagram: