js 數組的splice
splice():刪除、插入和替換
1、刪除:指定 2 個參數:要刪除的第一項的位置和要刪除的項數。
書寫格式:arr.splice( 0 , 2 )
2、插入:可以向指定位置插入任意數量的項,只需提供 3 個參數:起始位置、 0(要刪除的項數)和要插入的項。
書寫格式:arr.splice( 2,0,4,6 )
3、替換:可以向指定位置插入任意數量的項,且同時刪除任意數量的項,只需指定 3 個參數:起始位置、要刪除的項數和要插入的任意數量的項。插入的項數不必與刪除的項數相等。
書寫格式:arr.splice( 1,1,2,3 )
例子:
var arr = [1,3,5,7,9,11]; var arrRemoved = arr.splice(0,2); console.log(arr); //[5, 7, 9, 11] console.log(arrRemoved); //[1, 3] var arrRemoved2 = arr.splice(2,0,4,6); console.log(arr); // [5, 7, 4, 6, 9, 11] console.log(arrRemoved2); // [] var arrRemoved3 = arr.splice(1,1,2,4); console.log(arr); // [5, 2, 4, 4, 6, 9, 11] console.log(arrRemoved3); //[7]
此外介紹用了兩個數組方法,即pop()和unshift(),用splice實現
第一個:pop(),取出數組中的最后一項。
Array.prototype.pop2 = function () {
//數組中的最后一項
var res = this[this.length - 1];
//原數組去掉數組中的最后一項
this.splice(this.length - 1, 1);
return res
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] var res = arr.pop2(); alert(res) //9 alert(arr) //[1,2,3,4,5,6,7,8]
第二個:unshift,取出數組中的第一項。
Array.prototype.unshift2 = function () {
//數組中的第一項
var res = this[0];
//原數組去掉第一項
this.splice(0, 1);
return res
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] var res = arr.unshift2(); alert(res) //1 alert(arr) //[2,3,4,5,6,7,8,9]

浙公網安備 33010602011771號