Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

284
Vistas
How to add up all numbers from loop

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;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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`;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda