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