js splice方法----Array的方法
今天带来的是js的另外一个方法 splice
2、参数:arr.splice(index,howmany,element1,... ...,elementN);
3、参数解释: 1、index---------从该下标开始删除 2、howmany----删除指定数量的元素 3、elements-----插入的元素(可以为数组,感谢两位提醒)
4、实际使用的效果: var arr = new Array(6); arr[0] = "zero"; arr[1] = "one"; arr[2] = "two"; arr[3] = "three"; arr[4] = "four"; arr[5] = "five";
// 该数组对下面三个sample均视作新数组
sample1:
arr.splice(2,0,"six");
效果:["zero","one","six","two","three","four","five"]
解释:从第二个下标,删除0个元素,并插入一个"six"
sample2:
arr.splice(2,1,"six");
效果:["zero","one","six","three","four","five"]
解释:从第二个下标,删除1个元素("two"),并插入一个"six"--等同于替换index=3的元素,返回值为["two"]
sample3:arr.splice(2,3,"six");
效果:["zero","one","six","five"]
解释:从第二个下标,删除3个元素("two","three","four"),并插入一个"six" sample4:
arr.splice(2,1,"six","seven");
效果:["zero","one","six","seven","three","four","five]
解释:从第二个下标,删除1个元素,并插入"six","seven"
小结:splice先执行删除操作,删除指定个数的元素,然后再插入elements(元素或数组)
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: splice()的用法
- 下一篇: js数组操作方法concat()、slice()、splice()