Home > Blockchain >  Calculate the average of array elements in Javascript
Calculate the average of array elements in Javascript

Time:04-19

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

CodePudding user response:

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));
}
  • Related