slice()
返回一个索引和另一个索引之间的数据(不改变原数组),slice(start,end)有两个参数(start必需,end选填),都是索引,返回值不包括end
var heros=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heros.slice(1,4))// [ "蔡文姬", "韩信", "赵云" ]开始索引为1 结束索引为4(不包括4)
console.log(heros)// 不改变原数组 [ "李白", "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
若开始索引
为负数,则将该值加上数组长度后作为开始索引,如果此时还是负数,开始索引为0。
var heros=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heros.slice(-6,4))// [ "韩信", "赵云" ]开始索引为2 结束索引为4(不包括4)
console.log(heros.slice(-10,4))// [ "李白", "蔡文姬", "韩信", "赵云" ]开始索引为0 结束索引为4(不包括4)
如果开始索引大于或等于数组的长度或大于或等于结束索引,则slice()返回一个空数组。
var heros=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heros.slice(8,4))// [ ]
console.log(heros.slice(10,4))// [ ]
console.log(heros.slice(4,4)) //[ ]
console.log(heros.slice(5,4)) //[ ]
果结束索引
省略,截取到数组的末尾。如果为负,数组长度加上该值即为结束索引,如果此时还为负数,返回空数组
var heros=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heros.slice(1))// [ "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
console.log(heros.slice(1,-4))// [ "蔡文姬", "韩信", "赵云" ] 开始索引1 结束索引8+(-4)=4
console.log(heros.slice(1,-10)) //[ ] 开始索引1 结束索引8+(-10)=-2
splice()
用来添加或者删除数组的数据,只返回被删除的数据,类型为数组(改变原数组)
var heros=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
//当只有索引,从当前索引截取到最后
console.log(heros.splice(1))// [ "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
console.log(heros) //['李白']
当第二个参数(删除数量)小于0视为0
var heros=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heros.splice(1,-10))//[]
console.log(heros) // [ "李白", "蔡文姬", "韩信", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
删除并添加
var heros=["李白",'蔡文姬','韩信','赵云','甄姬','阿珂','貂蝉','妲己'];
console.log(heros.splice(1,2,['扁鹊'],'孙膑'))//[ "蔡文姬", "韩信" ]
console.log(heros) //[ "李白", [扁鹊], "孙膑", "赵云", "甄姬", "阿珂", "貂蝉", "妲己" ]
————————————————
来源:CSDN
作者:saturday-yh
链接:https://blog.csdn.net/qq_42092177/article/details/103922057