var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20];
myArray.splice(12, 4, 123, 432, 233, 98);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
// 123, 432, 233, 98, 16, 17, 18, 19, 20]
第一个参数 tosplice
是开始的索引,第二个是要删除的元素的数量,其余的是要插入的元素。因此,如果您插入与删除相同的号码,您最终会替换它们。
如果你确实希望它来自另一个数组,你可以试试这个,虽然它不是那么干净:
var oldArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 123,
432, 233, 98, 34, 35]
var newArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20];
[].splice.apply(newArray, [12, 4].concat(oldArray.slice(30, 30 + 4)));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
// 123, 432, 233, 98, 16, 17, 18, 19, 20]
这可能不如PointedEars 建议有效,但它非常简单,可能适用于许多用例。