JavaScript forEach()

forEach() 方法会调用一个函数并遍历数组的元素。forEach() 方法也可以用于 Map 和 Set。


JavaScript forEach

forEach() 方法的语法是:

array.forEach(function(currentValue, index, arr))

这里,

  • function(currentValue, index, arr) - 将为数组的每个元素运行的函数
  • currentValue - 数组的值
  • index (可选) - 当前元素的索引

arr (可选) - 当前元素的数组


forEach 与数组

forEach() 方法用于遍历数组。例如:

let students = ['John', 'Sara', 'Jack'];

// using forEach
students.forEach(myFunction);

function myFunction(item) {

    console.log(item);
}

输出

John
Sara
Jack

在上面的程序中,forEach() 方法接受 myFunction() 函数,该函数显示 students 数组的每个元素。


更新数组元素

正如我们在上面的示例中看到的,forEach() 方法用于遍历数组,更新数组元素非常简单。例如:

let students = ['John', 'Sara', 'Jack'];

// using forEach
students.forEach(myFunction);

function myFunction(item, index, arr) {

    // adding strings to the array elements
    arr[index] = 'Hello ' + item;
}

console.log(students);

输出

["Hello John", "Hello Sara", "Hello Jack"]

forEach 与箭头函数

您可以在 forEach() 方法中使用箭头函数来编写程序。例如:

// with arrow function and callback

const students = ['John', 'Sara', 'Jack'];

students.forEach(element => {
  console.log(element);
});

输出

John
Sara
Jack

for 循环到 forEach()

下面是用 for 循环和 forEach() 编写程序的示例。

使用 for 循环

const arrayItems = ['item1', 'item2', 'item3'];
const copyItems = [];

// using for loop
for (let i = 0; i < arrayItems.length; i++) {
  copyItems.push(arrayItems[i]);
}

console.log(copyItems);

输出

["item1", "item2", "item3"]

使用 forEach()

const arrayItems = ['item1', 'item2', 'item3'];
const copyItems = [];

// using forEach
arrayItems.forEach(function(item){
  copyItems.push(item);
})

console.log(copyItems);

for...of 与 Set

您可以使用 forEach() 方法遍历 Set 元素。例如:

// define Set
const set = new Set([1, 2, 3]);

// looping through Set
set.forEach(myFunction);

function myFunction(item) {
    console.log(item);
}

输出

1
2
3

forEach 与 Map

您可以使用 forEach() 方法遍历 Map 元素。例如:

let map = new Map();

// inserting elements
map.set('name', 'Jack');
map.set('age', '27');

// looping through Map
map.forEach (myFunction);

function myFunction(value, key) {
    
    console.log(key + '- ' + value);
}

输出

name- Jack
age- 27

在结束之前,让我们来测试一下你对 JavaScript forEach() 的了解!你能解决以下挑战吗?

挑战

编写一个函数来使向量中的每个项加倍。

  • 将数组 arr 中的每个项加倍并返回更新后的数组。
  • 例如,如果给定数组 arr[] = [2, 4, 6],则预期输出为 [4, 8, 12]
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战