I need some help. I'm trying to build an app that calculate the average of the given numbers. Yet, I'm a beginner and my array functions doesn't always work. I managed to display entered numbers but now I want to add them and calculate the average. I'm almost there. To calculate the average I will divide the sum by the array's length. But I can't add the numbers from the array to add. They are being concatenated or Nan is displayed. Should I use: Number() method somewhere?
BTW, I know for some of you this question may be pathetic but I'm a self-lerner and a bit of an old timer, so please don't downgrade this question. I tried to google answers but they didn't solve the problem.
let numbersEntered = document.querySelector("#numbersEntered");
let inputEl = document.querySelector("#input");
let numArr = [];
// buttons
let enterBtn = document.querySelector("#enter");
let avgBtn = document.querySelector("#avg");
enterBtn.addEventListener("click", displayNums);
function displayNums() {
let newNumber = Number(inputEl.value);
numArr.push(newNumber);
numbersEntered.innerHTML = "";
console.log(numArr);
for (let i = 0; i < numArr.length; i++) {
numbersEntered.innerHTML += numArr[i] + ",";
}
}
avgBtn.addEventListener("click", displayAvg);
// the below code is totally useless - I can't get the right sum
function displayAvg() {
let total = 0;
for (let i = 0; i < numArr.length; i++) {
total += numArr[i];
console.log(total);
}
}
<input type="text" id="input" />
<button id="enter" type="button">Enter</button>
<p id="numbersEntered"></p>
<button id="avg" type="button">Average</button>
<p id="average"></p>
</div>