js中的slice和splice

  1. slice(startIndex[, endIndex])
    功能:字符串和数组原型上都有slice方法,字符串调用slice方法可以返回子串,数组调用slice方法可以返回子数组。
    参数:
    startIndex: 可选,表示子串截取自原字符串的开始位置,不填默认为字符串开始位置;
    endIndex: 可选,表示子串截取自原字符串的结束位置(不包含该位置),不填默认至字符串结尾。
  • 针对string数据类型

情况1: 调用时不填写参数

var str = 'hello world'
var substr = str.slice()
console.log(substr)  //'hello world'

由上例可知,如果没填startIndex,则默认从位置0开始截取。
情况2:调用时只有startIndex, 没有endIndex

var str = 'hello world'
var substr = str.slice(1)
console.log(substr)  //'ello world'
console.log(str) //'hello world', 因此字符串调用slice方法不会对原字符串造成影响

由上例可知,如果没填endIndex,则默认截取到原字符串的末尾。
情况3:startIndex或endIndex为负数

var str = 'hello world'
var substr1 = str.slice(-3)
console.log(substr1)  //'rld'
var substr2 = str.slice(3, -3)
console.log(substr2)  //"lo wo"
var substr3 = str.slice(-3, 3)
console.log(substr3)  //""
var substr4 = str.slice(-4, -3)
console.log(substr4)  //"o"

由上例可知,slice的参数中如果出现负数(负数的绝对值要小于数组的长度),那么就按照的概念进行理解,负数 === str.length + 负数。另外要注意两点:(1)startIndex的模要小于endIndex的模,不然返回的结果为空字符串,如substr3。(2)startIndex和endIndex的绝对值要小于字符串长度,否则就默认为0。
情况4:endIndex大于str.length

var str = 'hello world'
var substr1 = str.slice(0,15)
console.log(substr1)  //'hello world'

由上例可知,如果endIndex的值大于字符串长度,则截取到字符串结尾。

  • 针对array数据类型
    array数据类型调用slice方法完全可以参考string数据类型。这里唯一要注意的是,对类数组对象调用slice方法可以转换成数组。
function list() {
   return Array.prototype.slice.call(arguments)
}
var argumentsArr = list(1,2,3) //[1, 2, 3]
  1. array.splice(start[, deleteCount[, item1[, item2[, …]]]])
    功能:splice方法只有数组类型支持,直接在原数组上添加或删除元素,返回被删除的元素组成的数组,如果没有删除元素,则返回空数组。
    参数:
    start: 可选,指定修改的开始位置(从0计数)。如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从-1计数);如果负数的绝对值大于数组的长度,则表示开始位置为第0位;
    deleteCount: 一般情况下必须填写,表示删除元素的个数,如果deleteCount的值大于start及之后元素的总个数,则将start及其之后的元素全部删除,如果deleteCount的值省略(splice方法只传入一个start参数),则同样将start及其之后的元素全部删除;
    item1, item2, …: 可选,要添加进数组的元素。
var arr = ['a', 'b', 'c', 'd'];
//一个参数都不传,相当于不做任何操作
var arr1 = arr.splice() //[]
//只有start一个参数,相当于删除start及其之后的所有元素
var arr2 = arr.splice(3) //['d']
//仅添加不删除元素
var arr3 = arr.splice(1, 0, 'd', 'e', 'f') //arr3的值为[], arr值为 ["a", "d", "e", "f", "b", "c"]
//删除一部分元素,同时添加一部分元素
var arr4 = arr.splice(1, 2, 'g') //arr4的值为["d", "e"], arr值为 ["a", "g", "f", "b", "c"]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章