/*
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)) // ''