splice()函数用法总结

splice() 方法用于添加或删除数组中的元素。

注意:这种方法会改变原始数组。并且splice()函数返回删除元素数组

splice函数的参数可以是一个到多个,下面我们按不同参数个数来实现不同的删除或者添加的功能。

第一种情况:只有1个参数的时候splice(index):表示从该index的位置开始,删除它(包括它自身)之后的所有的元素,代码如下:

let array = ['a','b','c','d'];
array.splice(2);
console.log(array);
//**************************
打印结果为[ 'a', 'b' ]

当splice(index)中的参数为负数的时候表示从数组长度减去index个元素(可以理解成从数组后面删),代码如下:

let array = ['a','b','c','d','e','f']
array.splice(-3)
console.log(array);
//*****************************************
打印结果为[ 'a', 'b', 'c' ]

第二种情况:2个参数的时候splice(index,count):表示从该index的位置开始删(包括自身),count表示删除数量。如果count小于等于0则不删除。代码如下:

let array = ['a','b','c','d','e','f']
array.splice(3,2)
console.log(array);
//*****************************
//打印结果为
[ 'a', 'b', 'c', 'f' ]
//第二个参数为0的时候或者小于0的时候,不会删除元素
let array = ['a','b','c']
array.splice(3,0)
console.log(array);
//*************************
打印结果
[ 'a', 'b', 'c' ]

第三种情况:3个及以上参数的时候splice(index,count,item1,....,item10):

1.当count为0的时候 不删除只添加,并从index位置开始添加这些item。代码如下:

let array = ['a','b','c']
array.splice(3,0,1)
console.log(array);
//*******************************
//打印结果为
[ 'a', 'b', 'c', 1 ]
------------ ------------ ---------- ----------
let array = ['a','b','c','d','e','f']
array.splice(3,0,1)
console.log(array);
//*******************************
//打印结果为
[ 'a', 'b', 'c', 1, 'd', 'e','f']
------------ ------------ ---------- ----------
let array = ['a','b','c','d','e','f']
array.splice(3,0,1,2,3)
console.log(array);
//*******************************
//打印结果为
[ 'a', 'b', 'c', 1, 2,  3, 'd', 'e','f']

1.当count为大于0的时候,删除且添加,并从index位置开始添加这些item,并且删掉index往后count个(不含本身)元素。比如count是2,就是删掉新数组index后面两个元素。代码如下:

let array = ['a','b','c','d','e','f']
array.splice(3,2,1,2,3)
console.log(array);
//*************************
打印结果
[ 'a', 'b', 'c', 1, 2,  3, 'f']

当index小于0的时候,表示从后往前数第几个下标。比如array.splice(-2,1,1,2,3)表示从后面数下标为2 的元素即d处插入1,2,3,且删掉d后面的1个元素即e,代码如下

let array = ['a','b','c','d','e','f']
array.splice(-2,1,1,2,3)
console.log(array);
//打印结果
[ 'a', 'b', 'c', 'd', 1, 2, 3, 'f' ]

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值