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

207
Vistas
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 Respuestas
Responde la pregunta

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 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