js字符串方法slice的实现逻辑:
const str = '123213';
String.prototype._slice = function (start = 0, end = this.length) {
if (!start && end === this.length) {
return this;
}
start *= 1;
end *= 1;
if (isNaN(start)) {
throw new Error('start is not a number')
}
if (isNaN(end)) {
throw new Error('end is not a number')
}
let str = '';
if (start > end) {
return str;
}
let startIndex = start,
endIndex = end;
if (startIndex < 0) {
startIndex = start + this.length
}
if (endIndex < 0) {
endIndex = end + this.length
}
for (let i = startIndex; i < endIndex; i++) {
str += this[i];
}
return str;
}
console.log(str.slice(0, 3));
// 输出结果:123