简体   繁体   中英

How can I push a number into an array?

I've been trying to push a number after the "for loop" into "x" but I cant use "x += count.push()" because it's not an array.

function partsSums(ls) {

   let count = 0;
   let x = []

   while (ls.length > 0) {
      for (let i = 0; i < ls.length; i++) {

         count += ls[i]
      }
      x += count;
      count = 0;
      ls.shift()
   }
   return x;
}

console.log(partsSums([0, 1, 3, 6, 10]));

I need to get x = [20, 20, 19, 16, 10, 0] and I'm getting 2020191610 instead. I'm pretty sure this is a no-brainer but I seem to be missing something...

You could reduce from the right.

 function partsSums(array) { return array.reduceRight((r, v) => [v + r[0], ...r], [0]); } console.log(partsSums([0, 1, 3, 6, 10]));

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