You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何forEach方法未手动传参仍能正常执行回调函数?

Why does forEach automatically pass arguments to my callback function?

Great question! This is one of those built-in JavaScript behaviors that trips up a lot of folks at first, but it makes total sense once you understand how forEach works under the hood.

Let's start with your code example to make this concrete:

var arr = [2, 3]; 
const addNum = (num) => console.log(num + 2); 
arr.forEach(addNum); 
// Console output: 4, 5

Here's the key thing: the forEach method is designed to automatically pass arguments to your callback function every time it runs through an element in the array. Specifically, it passes three arguments in order:

  • The current element being processed in the array (this is the num in your addNum function)
  • The index of the current element (you didn't declare this parameter, so it's ignored)
  • The original array that forEach was called on (also ignored here since you don't use it)

In your case, when forEach loops over arr:

  1. First iteration: It takes the element 2 and passes it as the first argument to addNum. Your function adds 2 to it, so 2 + 2 = 4 gets logged.
  2. Second iteration: It takes the element 3 and passes it as the first argument to addNum. That gives 3 + 2 = 5, which is the second log.

To prove this, you could modify your callback to accept all three parameters and see what happens:

const addNum = (num, index, originalArr) => {
  console.log(`Element: ${num}, Index: ${index}, Original Array: ${originalArr}`);
};
arr.forEach(addNum);
// Output:
// Element: 2, Index: 0, Original Array: 2,3
// Element: 3, Index: 1, Original Array: 2,3

You don't have to declare all the parameters—JavaScript just ignores any arguments that your function doesn't accept. That's why your original code works perfectly even though you didn't manually pass anything to addNum; forEach handles that part for you!

内容的提问来源于stack exchange,提问作者Syed Nouman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:38:13