發(fā)布時間:2015-02-10 編輯:www.jquerycn.cn
本文介紹下,,javascript中splice()方法的用法,,有需要的朋友作個參考吧,。
在javascript中splice()方法,,是一個很強(qiáng)的數(shù)組方法,,它有多種用法。
splice()主要用途是向數(shù)組的中部插入項(xiàng),。
有如下3種方式:
刪除——可以刪除任意數(shù)量的項(xiàng),,只需要指定2個參數(shù):要刪除的第一項(xiàng)的位置和要刪除項(xiàng)的項(xiàng)數(shù)。
例如,,splice(0,2)會刪除數(shù)組中的前兩項(xiàng)。
插入——可以向指定位置插入任意數(shù)量的項(xiàng),,只需要提供3個參數(shù):騎士位置,、0(要刪除的項(xiàng)數(shù))和要插入的項(xiàng),。
如果要插入多個項(xiàng),可以再傳入第四,、第五,,一直任意多個項(xiàng)。
例如,,splice(2,1,”red”,”green”)會刪除當(dāng)前數(shù)組位置2的項(xiàng),,然后再從位置2開始插入字符串“red”和”green”,。
替換——可以指向指定位置插入任意數(shù)量的項(xiàng),,且同時刪除任意數(shù)量的項(xiàng),,只需要指定3個指定參數(shù):起始位置,、要刪除的項(xiàng)數(shù)和要插入的任意數(shù)量項(xiàng),。
插入的像是不必與刪除的項(xiàng)數(shù)相等,。例如,,splice(2,2,”red”,”green”)會刪除當(dāng)前數(shù)組位置2的項(xiàng),然后再從位置2開始插入字符串“red”和“green”,。
splice()方法始終都會返回一個數(shù)組,該數(shù)組中包含從元素數(shù)組中刪除的項(xiàng)(如果沒有刪除任何項(xiàng),,則返回一個空數(shù)組),。
例子,使用splice方法的方式:
代碼示例:<script>
var colors = ["red", "green", "blue"];
var removed = colors.splice(0,1); //刪除第一項(xiàng)
Alert(colors); //green,blue
Alert(removed); //red,返回數(shù)組中值包含一項(xiàng)
removed = colors.splice(1, 0, "yellow", "orange"); //從位置1開始插入兩項(xiàng)
Alert(colors); //green,yellow,organge,blue
Alert(removed); //返回的是一個空數(shù)組
removed = colors.splice(1, 1, "red", "purple"); //插入兩項(xiàng),,刪除一項(xiàng)
Alert(colors); //green,red,purple,orange,blue
Alert(remove); //yellow, 返回的數(shù)組中只包含一項(xiàng)
</script>