JS:for数组中的每个项的当前值

JS: forEach item in array current value

本文关键字:for 数组 JS      更新时间:2023-09-26

我有一个由forEach调用的项数组。每次迭代时,我都想得到当前项的值。我该怎么做?

var bottom_array = [41,42,43,44]
bottom_array.forEach(function(){
    console.log(*current item*);
    })
console> 41
console> 42
console> 43
console> 44

提前感谢!

forEach函数使用一组参数调用给定的回调,这些参数允许您访问当前值等。

这些论点是:

  1. 当前值(这是您想要的)
  2. 当前索引
  3. 对数组的引用

您可以通过在回调函数中添加一个参数来获得所需内容,因为您不需要其他参数:

bottom_array.forEach(function (value) {
    console.log(value);
});
bottom_array.forEach(function(i){
    console.log(i);
    });