js截取数组slice(),splice()两种方法

slice()
返回一个索引和另一个索引之间的数据(不改变原数组),slice(start,end)有两个参数(start必需,end选填),都是索引,返回值不包括end

用法和截取字符串一样   https://blog.csdn.net/qq_43627981/article/details/99621402

var heroes=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heroes.slice(1,4))//  [ "蔡文姬", "韩信", "赵云" ]开始索引为1 结束索引为4(不包括4)
console.log(heroes)// 不改变原数组  [ "李白", "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
 如果开始索引为负数,将该值加上数组长度后作为开始索引,如果此时还为负数,开始索引为0。

var heroes=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heroes.slice(-6,4))//  [ "韩信", "赵云" ]开始索引为2 结束索引为4(不包括4)
console.log(heroes.slice(-10,4))//  [ "李白", "蔡文姬", "韩信", "赵云" ]开始索引为0 结束索引为4(不包括4)
如果开始索引大于或等于数组的长度,slice()返回空数组。 

var heroes=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heroes.slice(8,4))//  [ ]
console.log(heroes.slice(10,4))//  [ ]
console.log(heroes.slice(4,4)) //[ ]
console.log(heroes.slice(5,4)) //[ ]
如果结束索引省略,则截取到数组最后一位。如果为负,数组长度加上该值即为结束索引,如果此时还为负数,返回空数组。

var heroes=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heroes.slice(1))// [ "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
console.log(heroes.slice(1,-4))//  [ "蔡文姬", "韩信", "赵云" ] 开始索引1  结束索引8+(-4)=4
console.log(heroes.slice(1,-10)) //[ ] 开始索引1  结束索引8+(-10)=-2
splice()
用来添加或者删除数组的数据,只返回被删除的数据,类型为数组(改变原数组)

var heroes=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
//当只有索引,从当前索引截取到最后
console.log(heroes.splice(1))// [ "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
console.log(heroes) //['李白']
 当第二个参数(删除数量)小于0视为0。

var heroes=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heroes.splice(1,-10))//[]
console.log(heroes) // [ "李白", "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
删除并添加。

var heroes=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heroes.splice(1,2,['扁鹊'],'孙膑'))//[ "蔡文姬", "韩信" ]
console.log(heroes) //[ "李白",  [扁鹊], "孙膑", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值