Home > Net >  How to add up all numbers from loop
How to add up all numbers from loop

Time:03-30

I want something like this but I have no idea how to do this

https://i.stack.imgur.com/WQfHH.png

var number = document.getElementById('x').value;
        var i = 1;
        var sum = 0;
        while(i <= number){
            sum  = i;
            i  ;
        }
        document.getElementById('html').innerHTML = sum;

CodePudding user response:

const arr = (n) => new Array(n).fill(0).map((_, k) => k   1);
const calc = (n) => arr(n).reduce((prev, curr) => prev   curr, 0);
const log = (n) => console.log(n, '=>', arr(n).join('   '), '=', calc(n));

log(3);
log(5);

  • new Array(n) create an array with nth elements
  • .fill(0) fill the array with zeros
  • .map((_, k) => k 1) fill the array with integer (k is the index of the array, which is zero based)
  • .reduce() allow to calculate to sum of every element of the array
  • .join() will concatenate every element of the array to create the x y part

PS: Vincent was quicker but already have redacted my awnser

CodePudding user response:

If the intention is to output number lines, each with 1 2 ... = N, you could do:

let output = "";
for (n=1; n <= number; n  )
  output  = `${
                /* "1 2 ... n" */
                Array(n).fill().map((_,i) => i 1).join(" ")
             } = ${
                /* the sum */
                n * (n 1) / 2
             }\n`;
  • Related