JS手写 String slice 方法

本文详细解释了JavaScript中内置的`slice`方法以及自定义的`mySlice`函数,展示了如何使用它们对字符串进行截取,包括负索引和不指定结束索引的情况。
摘要由CSDN通过智能技术生成
/*
  slice 切 割
  注:此方法并不会改变原有的字符串,而是返回一个新的被截取/切割的新的字符串
  
  语法:
    string.slice(start, end)
  
  参数值:
    start:必选。 
          要抽取的片断的起始下标,默认位置为 0。
          如果为负数,start = string.length + start。
    end:可选。 
         紧接着要截取的片段结尾的下标。
         若指定的下标为0,则返回一个空的字符串。
         若未指定此参数,end = string.length。
         如果该参数是负数,end = start - end。
         
  slice(-2) 表示提取原数组中的倒数第二个元素到最后一个元素(包含最后一个元素)
  
  注:如果 start >= end 则返回一个空的字符串
     
  返回值:提取的字符串
*/
String.prototype.mySlice = function(start = 0, end) {
  if (end === 0) return ''
  start = start < 0 ? this.length + start : start
  end = !end ? this.length : (end < 0 ? start - end : end)

  if (start >= end) return ''
  let str = ''
  for (let i = start; i < end; i++) {
    str += this[i]
  }
  return str
}

// 测试代码
console.log('---------------- 1 ---------------------')
console.log('1===', 'jiaru-beauty'.slice()) // jiaru-beauty
console.log('1===', 'jiaru-beauty'.mySlice()) // jiaru-beauty

console.log('---------------- 2 ---------------------')
console.log('2===', 'jiaru-beauty'.slice(6)) // beauty
console.log('2===', 'jiaru-beauty'.mySlice(6)) // beauty

console.log('---------------- 3 ---------------------')
console.log('3===', 'jiaru-beauty'.slice(-6)) // beauty
console.log('3===', 'jiaru-beauty'.mySlice(-6)) // beauty

console.log('---------------- 4 ---------------------')
console.log('4===', 'jiaru-beauty'.slice(6, 0)) // ''
console.log('4===', 'jiaru-beauty'.mySlice(6, 0)) // ''

console.log('---------------- 5 ---------------------')
console.log('5===', 'jiaru-beauty'.slice(6, 3)) // ''
console.log('5===', 'jiaru-beauty'.mySlice(6, 3)) // ''

console.log('---------------- 6 ---------------------')
console.log('6===', 'jiaru-beauty'.slice(6, -3)) // 'bea'
console.log('6===', 'jiaru-beauty'.mySlice(6, -3)) // 'bea'

console.log('---------------- 7 ---------------------')
console.log('7===', 'jiaru-beauty'.slice(-6, 3)) // ''
console.log('7===', 'jiaru-beauty'.mySlice(-6, 3)) // ''

console.log('---------------- 8 ---------------------')
console.log('8===', 'jiaru-beauty'.slice(-6, -3)) // ''
console.log('8===', 'jiaru-beauty'.mySlice(-6, -3)) // ''

console.log('---------------- 9 ---------------------')
console.log('9===', 'jiaru-beauty'.slice(-6, 0)) // ''
console.log('9===', 'jiaru-beauty'.mySlice(-6, 0)) // ''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值