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
相关产品推荐
相关产品推荐

