【转】[JavaScript] 数组的 forEach 用法
转自:kimi.ai
forEach
方法用于对数组中的每个元素执行一次给定的函数。以下是其详细用法:基本语法
JavaScript复制
array.forEach(function(currentValue[, index[, array]]) {
// 执行的操作
}[, thisArg])
-
array
:要操作的数组。 -
function
:为数组中的每个元素执行的函数。-
currentValue
:当前正在处理的元素。 -
index
(可选):当前正在处理的元素的索引。 -
array
(可选):调用forEach
方法的数组。
-
-
thisArg
(可选):执行回调时使用的this
值。
示例
-
基本用法:打印数组中的每个元素JavaScript复制
let numbers = [1, 2, 3, 4, 5]; numbers.forEach(function(num) { console.log(num); }); // 输出: // 1 // 2 // 3 // 4 // 5
-
使用箭头函数简化代码JavaScript复制
let numbers = [1, 2, 3, 4, 5]; numbers.forEach(num => console.log(num)); // 输出: // 1 // 2 // 3 // 4 // 5
-
同时使用索引和数组参数JavaScript复制
let numbers = [1, 2, 3, 4, 5]; numbers.forEach((num, index, arr) => { console.log(`Element ${num} at index ${index} in array ${arr}`); }); // 输出: // Element 1 at index 0 in array [1, 2, 3, 4, 5] // Element 2 at index 1 in array [1, 2, 3, 4, 5] // Element 3 at index 2 in array [1, 2, 3, 4, 5] // Element 4 at index 3 in array [1, 2, 3, 4, 5] // Element 5 at index 4 in array [1, 2, 3, 4, 5]
-
处理对象数组JavaScript复制
let users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]; users.forEach(user => { console.log(`User ${user.name} with ID ${user.id}`); }); // 输出: // User Alice with ID 1 // User Bob with ID 2 // User Charlie with ID 3
-
使用
thisArg
参数JavaScript复制let numbers = [1, 2, 3, 4, 5]; let sum = 0; numbers.forEach(function(num) { this.sum += num; }, { sum: sum }); console.log(sum); // 15
注意事项
-
forEach
方法不会修改原数组,但可以在回调函数中修改数组的元素。 -
forEach
方法不会遍历数组中被删除或从未被赋值的元素。 -
forEach
方法的回调函数可以接受多个参数,但通常只需要使用currentValue
参数。如果需要使用索引或数组本身,可以按需添加。 -
forEach
方法可以与箭头函数一起使用,使代码更加简洁。 -
forEach
方法没有返回值(即返回undefined
),因此不能链式调用其他数组方法。 -
forEach
方法不会提前终止遍历,即使回调函数中包含return
语句。如果需要提前终止遍历,可以使用for
循环、for...of
循环或some
、every
方法。
与 for
循环的比较
虽然
forEach
方法可以方便地遍历数组,但在某些情况下,使用传统的 for
循环或 for...of
循环可能更灵活,例如需要提前终止遍历或需要更复杂的索引操作时。JavaScript复制
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) {
break; // 提前终止遍历
}
console.log(numbers[i]);
}
// 输出:
// 1
// 2
for (let num of numbers) {
if (num === 3) {
break; // 提前终止遍历
}
console.log(num);
}
// 输出:
// 1
// 2
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-01-17 【转】Git 报错:TLS certificate verification has been disabled!