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) //[ "李白",  [扁鹊], "孙膑", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐