
JavaScript 数组函数详解:slice、splice 和 forEach
JavaScript 提供丰富的内置数组方法,方便开发者操作和处理数组元素。本文重点介绍三种常用的数组方法:slice、splice 和 forEach,它们能显著提升数组操作的效率和代码简洁性。
1. slice() 方法
slice() 方法用于提取数组的一部分,不修改原始数组。它创建原始数组片段的浅拷贝,并返回一个新的数组。
语法:
array.slice(startIndex, endIndex);
-
startIndex:起始索引(包含该索引处的元素)。 -
endIndex:结束索引(不包含)。省略时,切片至数组末尾。
示例:
const arr = [1, 2, 3, 4, 5]; // 从索引 1 到索引 3 (不包含索引 3) 切片 const newArr = arr.slice(1, 3); console.log(newArr); // 输出: [2, 3]
省略 endIndex 参数,slice() 将从 startIndex 复制到数组末尾:
const arr = [1, 2, 3, 4, 5]; // 从索引 2 到末尾切片 const newArr = arr.slice(2); console.log(newArr); // 输出: [3, 4, 5]
负索引:
可以使用负索引从数组末尾开始切片:
立即学习“Java免费学习笔记(深入)”;
const arr = [1, 2, 3, 4, 5]; // 从索引 -3 到末尾切片 const newArr = arr.slice(-3); console.log(newArr); // 输出: [3, 4, 5]
2. splice() 方法
splice() 方法用于通过添加或删除元素来修改数组。它直接修改原始数组,可在特定索引处插入或删除元素。
语法:
array.splice(startIndex, deleteCount, item1, item2, ..., itemN);
-
startIndex:开始修改数组的索引。 -
deleteCount:从startIndex开始删除的元素数量。 -
item1, item2, ..., itemN:从startIndex开始添加到数组的元素。
示例:
const arr = [1, 2, 3, 4, 5]; // 从索引 2 删除 2 个元素 const removedElements = arr.splice(2, 2); console.log(arr); // 输出: [1, 2, 5] console.log(removedElements); // 输出: [3, 4]
splice() 也可用于添加元素:
const arr = [1, 2, 3, 4, 5]; // 在索引 2 处插入 6 和 7 arr.splice(2, 0, 6, 7); console.log(arr); // 输出: [1, 2, 6, 7, 3, 4, 5]
删除和添加结合:
splice() 可同时删除和添加元素:
const arr = [1, 2, 3, 4, 5]; // 删除索引 1 处的 2 个元素,并添加 6 和 7 arr.splice(1, 2, 6, 7); console.log(arr); // 输出: [1, 6, 7, 4, 5]
3. forEach() 方法
forEach() 方法用于迭代数组元素,并对每个元素应用一个函数。与 map() 或 filter() 不同,forEach() 不返回新数组,只执行回调函数的副作用(例如,打印或修改元素)。
语法:
array.forEach(callback(currentValue, index, array));
-
callback:对每个元素执行的函数。-
currentValue:当前处理的元素。 -
index:当前元素的索引。 -
array:调用forEach的数组。
-
示例:
const arr = [1, 2, 3, 4, 5];
// 打印数组的每个元素
arr.forEach(function(element) {
console.log(element);
});
// 输出:
// 1
// 2
// 3
// 4
// 5
使用箭头函数:
使用箭头函数可简化代码:
const arr = [1, 2, 3, 4, 5];
arr.forEach((element, index) => {
console.log(`索引 ${index}: ${element}`);
});
// 输出:
// 索引 0: 1
// 索引 1: 2
// 索引 2: 3
// 索引 3: 4
// 索引 4: 5
修改数组元素:
forEach() 主要用于执行副作用,不建议用于返回或修改数组。如果需要基于现有数组创建新数组,请使用 map()。
slice、splice 和 forEach 的比较
| 方法 | 目的 | 是否修改原始数组 | 返回值 |
|---|---|---|---|
slice |
提取数组一部分,不修改原始数组 | 否 | 新数组 (浅拷贝) |
splice |
添加/删除数组中特定位置的元素 | 是 | 被删除的元素 (数组) |
forEach |
对每个数组元素执行一个函数 | 否 | undefined |
结论
-
slice()适用于提取数组的一部分,且不修改原始数组。 -
splice()允许删除、替换或向数组添加元素,并直接修改原始数组。 -
forEach()适用于迭代数组元素并执行副作用,但不返回新数组。
熟练掌握这三种方法,能显著提升 JavaScript 数组操作的效率和代码可读性。
作者:Abhay Singh Kathayat
全栈开发者,精通前端和后端技术,擅长使用多种编程语言和框架构建高效、可扩展且用户友好的应用程序。 联系邮箱:kaashshorts28@gmail.com










