JavaScrip手写函数之slice函数(彻底弄懂包头不包尾)

一、slice函数介绍

  • slice函数用于数组和字符串的截取
  • 参数:start、end
  • start参数是截取开始位置,end是截取的结束位置。两个参数均为可选参数。
    • 当两个参数均不传是,截取全部
    • 当只传一个start时,从start开始到末尾
  • 参数也可为负数,网上很多都说从后面往前数,最正确的方法是负数+长度,使其变为正数。

二、手写slice

  • 数组slice
 Array.prototype.myslice =  function(start,end){
 	//判断参数是否为负数
    if(start&&end){			
        start = start<0?start = this.length+start:start
        end = end<0?end = this.length+end:end
    }
    if(!start) start = 0    	
    if(!end) end = this.length     判断参数是否有传
    let res=[];
   
    for(let i=start;i<end;i++){
        res.push(this[i])
    }

    return res
}


const arr = [1,2,3,4,5,6,7,8,9]

console.log(arr.myslice(4,7))
console.log(arr.myslice(-4,-2))
console.log(arr.myslice(2))
  • 字符串slice

与数组的slice基本一致

String.prototype.myslice =  function(start,end){
    if(start&&end){
        start = start<0?start = this.length+start:start
        end = end<0?end = this.length+end:end
    }
    if(!start) start = 0
    if(!end) end = this.length
    let res =''
   
    for(let i=start;i<end;i++){
        res +=this[i]
    }

    return res
}

const str = 'hello javascript'

console.log(str.myslice(4,9))
console.log(str.myslice(-6,-3))
console.log(str.myslice(3))

三、总结

slice使用规则
1、当两个参数都为正数时:包头不包尾
2、当两个参数都为负数时:两个参数加上length变为正数,再包头不包尾。(还有一种方法是包尾不包头)
3、当两个参数一正一负时,最好加上length变为正数时最容易判断。

  • 试练
const str = 'hello javascript'

console.log(str.myslice(-4,9))
console.log(str.myslice(-6,-3))
console.log(str.myslice(-2))

你可能感兴趣的:(Javascript之手写函数,javascript,前端,开发语言,react.js,原型模式)