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

206
Visualizações
Calculate the average of array elements in Javascript

I got this Javascript exercise. The average should be 11.2, but my program returned 5420502.4.


Define an empty array. Also create two functions:

addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array.

printInfo() outputs the amount of elements in the array to the console, then the average of their values.

The HTML document has two buttons for calling the functions.


var arr = [];

function addNumber() {
    var num = document.getElementById("num").value;
    return arr.push(num);
}

function printInfo() {
    var len = arr.length;
    console.log("The array has " + len + " elements.");
    
    var total = 0;
    for (var i = 0; i < len; i++) {
        total += arr[i]; // replace arr[i] with +arr[i]
    }
    var avg = total / len;
  // additionally render result to UI
  document.getElementById("info").innerText = avg;
    return console.log("The average of the values is " + avg);
}
.outerStyle { border: 2px solid black; width: 45%; }
.inpStyle { padding: 10px; margin: 10px; }
button { margin: 10px; }
<div id="outer" class="outerStyle">
  <div class="inpStyle">
    <label for="num">Enter number: </label>
    <input id="num" type="number" />
  </div>
  <button id="addBtn" onclick="addNumber()">Add</button>
  <button id="printInfo" onClick="printInfo()">Print Info</button>
  <hr/>
  <div id="info" />
</div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The value from your input is a string. So, it will concatenate in to total. If your input value was 1 and you added it to the array twice, your array would consist of 2 strings, "1" and "1". Then, you're adding this, which makes "11" because you're adding strings together.

You'll want to use something like parseInt to convert the string to a number first.

function addNumber() {
    var num = document.getElementById("num").value;
    return arr.push(parseInt(num));
}
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