JS数组方法之splice()

2017-04-03  本文已影响52人  元气满满321

splice():增删数组元素

array.splice(index)
array.splice(index,howmany)
array.splice(index,howmany,item1,.....,itemX)

例子:

删除数组下标1号位置以后的所有元素

var arr = ['apple','pear','orange','grape'];
var removed = arr.splice(1);
//arr is ['apple']
//removed is ['pear','orange','grape']

从数组下标2号位置开始删除两个元素

var arr = ['apple','pear','orange','grape'];
var removed = arr.splice(2,2);
//arr is ['apple','pear']
//removed is ['orange','grape']

从数组下标2号位置开始删除1个元素,并插入“peach”,"banana"

var arr = ['apple','pear','orange','grape'];
var removed = arr.splice(2,1,"peach","banana");
//arr is ['apple','pear','peach','banana','grape']
//removed is ['orange']

是不是很简单?来,给个题做做
给定数组 var arr = ['a','b','c']
(1)删除b元素?
(2)再把刚才删除的b元素添加回来?
欢迎留言告诉我


上一篇下一篇

猜你喜欢

热点阅读