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

JS使用forEach遍历计算时函数返回undefined问题求解

问题根因

Array.prototype.forEach 本身设计为无返回值的遍历方法,你在forEach传入的回调函数里写的return语句,仅会结束当前单次回调的执行,不会把值传递到外层函数。
你当前实现的number函数全程没有对外返回计算结果的语句,按照JS的语法规则,没有显式return的函数默认返回undefined,这就是你拿到undefined、但循环内打印total能看到正确值的原因——total确实算对了,只是你没把它从函数里抛出来。

修复方案
  • 保留forEach写法的话,只需要在遍历全部结束后,手动return计算完成的total即可,回调里的return语句是无效代码可以直接删掉:
var number = function(busStops){
  var total = 0;
  busStops.forEach(function(n){
    total = total + n[0] - n[1];
  })
  return total;
}
  • 这种累加类场景更推荐用reduce实现,代码更简洁,不需要额外维护临时遍历:
const number = (busStops) => busStops.reduce((total, [getOn, getOff]) => total + getOn - getOff, 0);

上述两种写法调用number([[10,0],[3,5],[5,8]])时,都会正确返回计算结果5。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:30:10