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

本文详细讲解了Python和JavaScript中的slice函数用法,包括参数解释、正负数截取技巧和实例演示。重点介绍了如何处理负数索引并遵循包头不包尾的原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

名字还没想好☜

祝福你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值