在 JavaScript 中,可以使用以下方法来切片一个数组,而不使用内置的 slice
方法:
Array.from
方法:function sliceArray(arr, startIndex, endIndex) {
return Array.from(arr, (item, index) => {
if (index >= startIndex && index < endIndex) {
return item;
}
}).filter(Boolean);
}
// 示例用法
const arr = [1, 2, 3, 4, 5];
const slicedArr = sliceArray(arr, 1, 4);
console.log(slicedArr); // 输出: [2, 3, 4]
Array.prototype.reduce
方法:function sliceArray(arr, startIndex, endIndex) {
return arr.reduce((acc, item, index) => {
if (index >= startIndex && index < endIndex) {
acc.push(item);
}
return acc;
}, []);
}
// 示例用法
const arr = [1, 2, 3, 4, 5];
const slicedArr = sliceArray(arr, 1, 4);
console.log(slicedArr); // 输出: [2, 3, 4]
这些方法都可以通过遍历给定的数组,并根据指定的起始索引和结束索引来选择要切片的元素,然后返回一个新的切片数组。