js slice实现
slice 方法的基本用法
slice 是 JavaScript 数组和字符串的一个内置方法,用于提取部分内容并返回一个新数组或字符串,不改变原数组或字符串。以下是具体用法:

数组的 slice 方法
语法:array.slice(startIndex, endIndex)

startIndex:开始提取的索引(包含),默认为 0。endIndex:结束提取的索引(不包含),默认为数组长度。- 返回从
startIndex到endIndex(不含)的新数组。
const arr = [1, 2, 3, 4, 5];
const subArr = arr.slice(1, 4); // [2, 3, 4]
字符串的 slice 方法
语法:string.slice(startIndex, endIndex)
参数与数组类似,返回提取的子字符串。
const str = "Hello, world!";
const subStr = str.slice(0, 5); // "Hello"
负索引和默认值
- 负索引:表示从末尾开始计算。例如,
-2表示倒数第二个元素。 - 省略参数:
- 省略
endIndex:提取到末尾。 - 省略所有参数:返回完整副本。
- 省略
const arr = [1, 2, 3, 4, 5];
arr.slice(-3); // [3, 4, 5]
arr.slice(1); // [2, 3, 4, 5]
arr.slice(); // [1, 2, 3, 4, 5](浅拷贝)
实现自定义 slice 方法
以下是一个模拟 slice 功能的实现(以数组为例):
function customSlice(array, start, end) {
const result = [];
const length = array.length;
// 处理 start 的默认值和负数
start = start === undefined ? 0 : start;
start = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
// 处理 end 的默认值和负数
end = end === undefined ? length : end;
end = end < 0 ? Math.max(length + end, 0) : Math.min(end, length);
// 提取元素
for (let i = start; i < end; i++) {
result.push(array[i]);
}
return result;
}
// 示例
const arr = [1, 2, 3, 4, 5];
console.log(customSlice(arr, 1, 4)); // [2, 3, 4]
关键点说明
- 边界处理:确保
start和end在合理范围内(非负且不超过数组长度)。 - 浅拷贝:
slice返回的新数组是浅拷贝,嵌套对象或数组仍共享引用。 - 字符串实现:字符串的
slice类似,但需通过字符索引提取子串。
通过以上方法,可以灵活提取数组或字符串的子集,适用于分割、复制等场景。






