JavaScript 的 forEach()
提示
forEach()
方法的用法:forEach()
用于遍历数组或其他可迭代对象(如 Maps 和 Sets),它执行每个元素上的回调函数,该回调函数可以接收当前元素值、索引和数组本身作为参数。- 更新数组元素:在
forEach()
方法的回调函数中,可以直接修改原数组的元素,例如添加字符串前缀。 forEach()
与其他循环的比较:forEach()
可以作为for
循环或for...of
循环的替代,提供更简洁的语法来遍历数组、Sets 或 Maps。
forEach()
方法调用一个函数并遍历数组的元素。forEach()
方法也可以用于 Maps 和 Sets。
JavaScript forEach
forEach()
方法的语法是:
array.forEach(function(currentValue, index, arr))
这里,
- function(currentValue, index, arr) - 用于每个数组元素运行的函数
- currentValue - 数组的值
- index (可选) - 当前元素的索引
arr (可选) - 当前元素的数组
在数组中使用 forEach
forEach()
方法用于遍历数组。例如,
let students = ["John", "Sara", "Jack"];
// 使用 forEach
students.forEach(myFunction);
function myFunction(item) {
console.log(item);
}
输出
John
Sara
Jack
在上面的程序中,forEach()
方法采用 myFunction()
函数来显示 students
数组的每个元素。
更新数组元素
正如我们在上面的示例中所见,forEach()
方法用于遍历数组,更新数组元素相当简单。例如,
let students = ["John", "Sara", "Jack"];
// 使用 forEach
students.forEach(myFunction);
function myFunction(item, index, arr) {
// 向数组元素添加字符串
arr[index] = "Hello " + item;
}
console.log(students);
输出
["Hello John", "Hello Sara", "Hello Jack"];
使用箭头函数的 forEach
您可以使用箭头函数与 forEach()
方法编写程序。例如,
// 使用箭头函数和回调
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 = [];
// 使用 for 循环
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 = [];
// 使用 forEach
arrayItems.forEach(function (item) {
copyItems.push(item);
});
console.log(copyItems);
使用 for...of 遍历 Sets
您可以使用 forEach()
方法遍历 Set 的元素。例如,
// 定义 Set
const set = new Set([1, 2, 3]);
// 遍历 Set
set.forEach(myFunction);
function myFunction(item) {
console.log(item);
}
输出
1
2
3
使用 forEach 遍历 Maps
您可以使用 forEach()
方法遍历 Map 的元素。例如,
let map = new Map();
// 插入元素
map.set("name", "Jack");
map.set("age", "27");
// 遍历 Map
map.forEach(myFunction);
function myFunction(value, key) {
console.log(key + "- " + value);
}
输出
name - Jack
age - 27