简体   繁体   中英

javascript reduce function sum of all array values

   for (var j = 0; j < l; j++) {
      aa = (j*5)/12/100;

      const arr = [ { x: aa } ];
      const result = arr.reduce( ( sum, { x } ) => sum + x , 0);
      console.log( result );

    }

I have tried to sum of all output numbers using javascript reduce. But, counldn't able to achieve the desired output. This aa variable returns 5 for first 12 counts and then returns 10 for next 12 counts. So, I want this line console.log(result) should return 180 ((5*12)+(10*12)). But, it returns 5 and 10 in console.

If you want to do it like this, then you should try:

 const arr = []; for (var j = 0; j < 10; j++) { let aa = (j*5)/12/100; arr.push({ x: aa }); } const result = arr.reduce( ( sum, { x } ) => sum + x , 0); console.log( result ); 

else you're re-declaring result and arr at every iteration.

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