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

为何JavaScript中forEach搭配箭头函数的代码无法正常运行?

Why Your Code Isn't Outputting What You Expect

Hey there! Let's break down the issue with your code. The problem comes down to how the forEach method works in JavaScript.

The Core Issue: forEach Returns undefined

When you run console.log(array3.forEach(function5)), you're logging the return value of forEach—and forEach always returns undefined, no matter what your callback does. It's designed to iterate over the array and execute your callback function for each element, but it doesn't generate or return a new array of results.

Fixes to Get the Output You Want

Here are a few ways to adjust your code to get the index-element strings you're looking for:

1. Print Directly Inside forEach

If you just want to log each index-element pair to the console, move the console.log into your callback function and remove the outer console.log:

const array3 = [5, 10, 15, 20, 25, 30, 35, 40]; 
const function5 = (index, element) => {console.log(index + ": " + element)}; 
array3.forEach(function5);

2. Use map to Generate a Result Array

If you want to create an array of the index-element strings (so you can log or use them later), use the map method instead. map returns a new array with the results of running your callback on every element:

const array3 = [5, 10, 15, 20, 25, 30, 35, 40]; 
const function5 = (index, element) => {return index + ": " + element}; 
const formattedArray = array3.map(function5);
console.log(formattedArray);

This will output: ["0: 5", "1: 10", "2: 15", ..., "7: 40"]

3. Collect Results Manually with forEach

If you really need to use forEach (though map is cleaner for this use case), you can create an empty array and push each result into it during iteration:

const array3 = [5, 10, 15, 20, 25, 30, 35, 40]; 
const result = [];
const function5 = (index, element) => {result.push(index + ": " + element)}; 
array3.forEach(function5);
console.log(result);

Quick Recap

  • Use forEach when you need to perform an action (like logging, updating DOM elements, or modifying external variables) for each element, but don't need a returned array.
  • Use map when you need to transform each element into a new value and get a new array of those transformed values.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:01:05