【转】[JavaScript] 数组的 forEach 用法
转自:kimi.com
forEach 方法用于对数组中的每个元素执行一次给定的函数。以下是其详细用法:基本语法
JavaScript复制
array.forEach(function(currentValue[, index[, array]]) {
// 执行的操作
}[, thisArg])
-
array:要操作的数组。 -
function:为数组中的每个元素执行的函数。-
currentValue:当前正在处理的元素。 -
index(可选):当前正在处理的元素的索引。 -
array(可选):调用forEach方法的数组。
-
-
thisArg(可选):执行回调时使用的this值。
示例
-
基本用法:打印数组中的每个元素JavaScript复制
let numbers = [1, 2, 3, 4, 5]; numbers.forEach(function(num) { console.log(num); }); // 输出: // 1 // 2 // 3 // 4 // 5 -
使用箭头函数简化代码JavaScript复制
let numbers = [1, 2, 3, 4, 5]; numbers.forEach(num => console.log(num)); // 输出: // 1 // 2 // 3 // 4 // 5 -
同时使用索引和数组参数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] -
处理对象数组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 -
使用
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循环或some、every方法。
与 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
浙公网安备 33010602011771号