为何forEach方法未手动传参仍能正常执行回调函数?
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
numin youraddNumfunction) - The index of the current element (you didn't declare this parameter, so it's ignored)
- The original array that
forEachwas called on (also ignored here since you don't use it)
In your case, when forEach loops over arr:
- First iteration: It takes the element
2and passes it as the first argument toaddNum. Your function adds 2 to it, so2 + 2 = 4gets logged. - Second iteration: It takes the element
3and passes it as the first argument toaddNum. That gives3 + 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

