这个函数通过数组,在每个对象中添加第一个数字并减去第二个数字。
例如:数(10,0,3,5,5,8)= (10-0) + (3-5) + (5-8)总数应等于5
问题:我使用的是forEach循环,但它会返回未定义的值,当我将数字显示为5时。
var number = function(busStops){
var total = 0;
busStops.forEach(function(n){
total = total + n[0] - n[1];
return total;
})
}发布于 2022-06-30 21:03:29
你可以减少数组。
const
number = busStops => busStops.reduce((t, [a, b]) => t + a - b, 0);
console.log(number([[10, 0], [3, 5], [5, 8]]));
发布于 2022-06-30 20:59:21
刚刚发现问题,返回应该在forEach循环之外
var number = function(busStops){
var total = 0;
busStops.forEach(function(n){
total = total + n[0] - n[1];
})
return total;
}https://stackoverflow.com/questions/72821912
复制相似问题