Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

283
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda