随笔 - 748  文章 - 1  评论 - 107  阅读 - 34万

【转】[JavaScript] 数组的 forEach 用法

转自:kimi.ai

forEach 方法用于对数组中的每个元素执行一次给定的函数。以下是其详细用法:

基本语法

JavaScript复制
array.forEach(function(currentValue[, index[, array]]) {
    // 执行的操作
}[, thisArg])
  • array:要操作的数组。
  • function:为数组中的每个元素执行的函数。
    • currentValue:当前正在处理的元素。
    • index(可选):当前正在处理的元素的索引。
    • array(可选):调用 forEach 方法的数组。
  • thisArg(可选):执行回调时使用的 this 值。

示例

  1. 基本用法:打印数组中的每个元素
    JavaScript复制
    let numbers = [1, 2, 3, 4, 5];
    numbers.forEach(function(num) {
        console.log(num);
    });
    // 输出:
    // 1
    // 2
    // 3
    // 4
    // 5
  2. 使用箭头函数简化代码
    JavaScript复制
    let numbers = [1, 2, 3, 4, 5];
    numbers.forEach(num => console.log(num));
    // 输出:
    // 1
    // 2
    // 3
    // 4
    // 5
  3. 同时使用索引和数组参数
    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]
  4. 处理对象数组
    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
  5. 使用 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 循环或 someevery 方法。

与 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
posted on   z5337  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-01-17 【转】Git 报错:TLS certificate verification has been disabled!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示