Js-基础语法学习-splice()方法

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

定义:
1. splice() 方法用于添加或删除数组中的元素
2. splice() 方法会改变原数组
参数:
1. index : 必填。从何处开始添加或删除
2. howmany :可选。删除多少个元素。若不填,则默认删除从index直到数组结尾所有元素
3. item :用于替换的时候替补的值

用法一:array.splice(index)

  1. 删除数组中从下标为index开始直到结尾的所有元素

var listA = ['a','b','c','d','e']
console.log('listA -----> ',listA)
var res = listA.splice(1)    // 将删除了元素之后的数组赋值给 res
console.log('res -----> ',res)
console.log('listA -----> ',listA)    // 原数组被改变

运行结果:

  1. 删除数组中最后一位元素

var listA = ['a','b','c','d','e']
console.log('listA -----> ',listA)
var res = listA.splice(-1)
console.log('res -----> ',res)
console.log('listA -----> ',listA)

运行结果:


用法二:array.splice(index, howmany)

  1. 删除数组中下标为index的元素

var listA = ['a','b','c','d','e']
console.log('listA -----> ',listA)
var res = listA.splice(0,1)    // 删除数组中下标为 0 的元素
console.log('res -----> ',res)
console.log('listA -----> ',listA)

执行结果:

  1. 删除数组中从下标为1开始,共删除三个

var listA = ['a','b','c','d','e']
console.log('listA -----> ',listA)
var res = listA.splice(1,3)
console.log('res -----> ',res)
console.log('listA -----> ',listA)

执行结果:

用法三:array.splice(index, howmany, item1, item2, ... itemN)

  1. 替换数组中从下标为1开始的一共三位元素为item1、item2、item3

var listA = ['a','b','c','d','e']
console.log('listA -----> ',listA)
var res = listA.splice(1,3,'bb','cc','dd')
console.log('res -----> ',res)
console.log('listA -----> ',listA)

执行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值