简体   繁体   中英

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). 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.

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.

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.

Finally move the console.log out of the loop:

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. It is a pretty bad way to to dit, because not really readable. Better use parseInt or parseFloat functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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