JavaScript 中數組的 splice() 方法

splice( 開始的位置,要刪除的個數 [,插入的項1 ] [,插入的項2 ][...] )

直接對原數組進行處理,返回一個數組,包含從原數組中刪除的項

1、刪除任意位置項 ------ 傳入兩個參數,第二個參數不爲0;

2、從任意位置添加新項 ----- 傳入三個及以上參數,第二個參數爲0;

3、替換任意位置項 ----- 傳入三個及以上參數,第二個參數不爲0。

var colors = ["red", "green", "blue"];

var removed = colors.splice(0,1);              //刪除第一項
alert(colors);        //green,blue
        
removed = colors.splice(1, 0, "yellow", "orange");  //從位置1開始插入兩項
alert(colors);       //green,yellow,orange,blue

removed = colors.splice(1, 1, "red", "purple");    //將第二項替換爲傳入的兩項
alert(colors);       //green,red,purple,orange,blue

如果只傳入一個參數,表示數組從該位置開始,截取到數組末尾,返回截取的數組,原數組變爲剩餘的部分

var colors = ["red", "green", "blue","red", "green", "blue","red", "green", "blue"];
var newColors = colors.splice(4);
alert(newColors)        //["green", "blue", "red", "green", "blue"]
alert(colors)        //["red", "green", "blue", "red"]
對比用兩個參數刪除數組的做法
var colors = ["red", "green", "blue","red", "green", "blue","red", "green", "blue"];
var newColors = colors.splice(0,4)
alert(newColors)        //["red", "green", "blue", "red"]
alert(colors)        //["green", "blue", "red", "green", "blue"]
上面的例子說明,在使用splice截取數組的時候,傳入的參數不同,要注意需要取返回值,還是取改變後的原數組。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章