forEach() 在JavaScript中运用

forEach() 是 JavaScript 中用于遍历数组的一种方法。它为数组中的每个元素执行一次提供的回调函数。

基本语法

array.forEach(function(currentValue, index, array) { // 你的代码 });
  • currentValue:当前处理的元素。
  • index(可选):当前处理元素的索引。
  • array(可选):正在操作的数组。

栗子:

示例 1:遍历数组并打印每个元素

const array = [1, 2, 3, 4, 5]; 
array.forEach(function(element) { console.log(element); });

输出:

1
2
3
4
5

示例 2:使用箭头函数

const array = [1, 2, 3, 4, 5]; 
array.forEach(element => console.log(element));

 输出:

1
2
3
4
5

示例 3:访问索引和数组本身

const array = [1, 2, 3, 4, 5]; 
array.forEach((element, index, array) => { 
console.log('Element:', element); 
console.log('Index:', index); 
console.log('Array:', array); 
});

输出:

Element: 1
Index: 0
Array: [1, 2, 3, 4, 5]
Element: 2
Index: 1
Array: [1, 2, 3, 4, 5]
Element: 3
Index: 2
Array: [1, 2, 3, 4, 5]
Element: 4
Index: 3
Array: [1, 2, 3, 4, 5]
Element: 5
Index: 4
Array: [1, 2, 3, 4, 5]

示例 4:修改原数组中的元素

虽然 forEach() 不直接修改数组,但你可以在回调函数中修改数组的元素:

const array = [1, 2, 3, 4, 5];
 array.forEach((element, index, array) => { 
 array[index] = element * 2; 
}); 
console.log(array);

输出:

[2, 4, 6, 8, 10]

示例 5:计算数组元素的总和

const array = [1, 2, 3, 4, 5]; 
let sum = 0; array.forEach(element => { 
sum += element; 
}); 
console.log('Sum:', sum);

输出:

Sum: 15

注意事项

  • forEach() 不会改变原数组的结构,但可以改变数组元素的值。
  • forEach() 不会对添加到数组之后的元素进行操作。
  • forEach() 不会执行已经删除的数组元素。
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值