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