简体   繁体   English

如何总结我在 forEach 循环中生成的变量中的数字列表

[英]How can I sum up a list of numbers inside a variable which I generated inside a forEach loop

I have made a for each loop to access numbers from a JSON array, the array will be dynamic and forever changing and so I have isolated the numbers inside a variable (the variable is inside the loop).我为每个循环创建了一个从 JSON 数组访问数字的循环,该数组将是动态的并且永远变化,因此我将数字隔离在一个变量中(变量在循环内)。 My question is: How do I sum up the numbers that are in the variable.我的问题是:我如何总结变量中的数字。

I tried doing a for loop inside the loop but it didn't work.我尝试在循环内执行 for 循环,但没有奏效。

it looks kind of like this:它看起来有点像这样:

 const arrayhours = Array.from(json_obj);
 arrayhours.forEach(e=>{ 
              const hours = parseFloat(e.hoursWorked);

console.log(hours); //returns for example 1.25 9 5 8 7 as seperate objects.
});

控制台日志的图像

You can use Array.reduce() for getting sum of numbers in an array.您可以使用Array.reduce()来获取数组中的数字总和。

const arrayhours = Array.from(json_obj);
arrayhours.forEach(e=>{ 
  const hours = parseFloat(e.hoursWorked);
  console.log(hours); //returns for example 1.25 9 5 8 7 as seperate objects.
});
const sum = arrayhours.reduce((acc, val) => acc + parseFloat(val.hoursWorked), 0)

Initialize the variable with let hours = 0 before the loop and then use += to add something (instead of = ) to assign something.在循环之前使用let hours = 0初始化变量,然后使用+=添加一些东西(而不是= )来分配一些东西。

Finally move the console.log out of the loop:最后将console.log移出循环:

const arrayhours = Array.from(json_obj);
let hours = 0;
arrayhours.forEach(e => { 
  const hours += parseFloat(e.hoursWorked);
});
console.log(hours);

const sum = arrayhours.reduce((acc, curr) => acc + parseFloat(curr.hoursWorked, 10), 0)

In comment, AZ_ is using +c.hoursWorked which is a JS trick to cast (if possible) a string into an Int.在评论中,AZ_ 正在使用+c.hoursWorked ,这是将字符串转换(如果可能)为 Int 的 JS 技巧。 It is a pretty bad way to to dit, because not really readable.这是一种非常糟糕的方式,因为不是真正可读的。 Better use parseInt or parseFloat functions.最好使用 parseInt 或 parseFloat 函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM