[英]forEach returning undefined
此函数遍历数组并在每个对象中添加第一个数字并减去第二个数字
例如。 number([[10,0],[3,5],[5,8]]) = (10-0) + (3-5) + (5-8) 总计应该等于 5
问题:我正在使用 forEach 循环,但它返回未定义,当我 console.log 数字显示 5。
var number = function(busStops){
var total = 0;
busStops.forEach(function(n){
total = total + n[0] - n[1];
return total;
})
}
你可以减少数组。
const number = busStops => busStops.reduce((t, [a, b]) => t + a - b, 0); console.log(number([[10, 0], [3, 5], [5, 8]]));
刚刚发现问题,返回应该在forEach循环之外
var number = function(busStops){
var total = 0;
busStops.forEach(function(n){
total = total + n[0] - n[1];
})
return total;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.