美文网首页
JS数组方法之splice()

JS数组方法之splice()

作者: 元气满满321 | 来源:发表于2017-04-03 17:13 被阅读52次

    splice():增删数组元素

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

    • 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元素添加回来?
    欢迎留言告诉我


    相关文章

      网友评论

          本文标题:JS数组方法之splice()

          本文链接:https://www.haomeiwen.com/subject/cpgbgttx.html