📜  JavaScript数组forEach()(1)

📅  最后修改于: 2023-12-03 15:16:18.162000             🧑  作者: Mango

JavaScript数组forEach()

在 JavaScript 中,数组是非常重要且常用的数据类型。而对于数组的操作,尤其是遍历操作,forEach() 是一个非常好用的方法。

简介

forEach() 方法是 ES5 提出的一种针对数组的遍历方法,用来对数组中的每个元素执行指定的操作。forEach() 接受一个回调函数作为参数,该回调函数会被 forEach() 执行的每个元素调用一次。forEach() 方法只能用于数组类型。

语法
array.forEach(function(currentValue, index, arr), thisValue)

参数解释:

  • function(currentValue, index, arr): 必需,数组中的每个元素都会执行该函数,参数解释如下:
    • currentValue: 必需,当前元素的值。
    • index: 可选,当前元素的下标。
    • arr: 可选,当前正在被遍历的数组。
  • thisValue: 可选,当调用回调函数时,用作 this 关键字的值。
示例

下面是一些使用 forEach() 方法的示例。

// 遍历数组
const animals = ['cat', 'dog', 'lion'];
animals.forEach(function(animal, index) {
    console.log(index + ': ' + animal);
});
// Output:
// 0: cat
// 1: dog
// 2: lion

// 遍历对象
const obj = { name: 'John', age: 25 };
Object.keys(obj).forEach(function(key) {
    console.log(key + ': ' + obj[key]);
});
// Output:
// name: John
// age: 25

// 修改数组
const numbers = [1, 2, 3, 4];
numbers.forEach(function(number, index, arr) {
    arr[index] = number * 2;
});
console.log(numbers); // Output: [2, 4, 6, 8]
注意事项
  • 回调函数是 forEach() 方法的核心,确保传递一个函数作为参数。
  • 如果没有指定 thisValue,回调函数中的 this 关键字会被设置为全局对象(在浏览器中为 window 对象)。
  • 不能在 forEach() 方法中使用 return 关键字来停止遍历。
  • 尽管 forEach() 方法返回值为 undefined,但可以使用 breakcontinue 关键字来控制遍历的行为。
总结

forEach() 方法是一种非常好用的数组遍历方法,可以快捷地对数组中的每个元素进行操作。在编写 JavaScript 程序时,尤其是对于大型项目来说,掌握 forEach() 方法是非常重要的。