Planned output:
The array has 10 elements.
The average of the values is 36.1
I plan two functions: addNumber() and printInfo().
Function: addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array.
Another function: printInfo() outputs the amount of elements in the array to the console, then the average of their values.
HTML document has two buttons for calling the functions.
I wrote:
let arr = [];
arr.push (function addNumber() {
let element = document.getElementById("num");
})
function printInfo() {
console.log (arr.length );
}
How to use buttons for calling the functions in HTML?
How to count average of values in the array?
Hello here is a working example. https://jsfiddle.net/7t41y80m/
HTML Example
<fieldset>
<legend>Array List</legend>
<label id="lbl">1,2,3,4,5,6,7,8,9</label>
<input type="number" id="input">
<button onclick="AddNumber();">Add Number</button>
</fieldset>
<button onclick="CalculateAvg();">Print Averrage</button>
Javascript:
function CalculateAvg()
{
const arr = document.getElementById('lbl').innerText.split(',').map(Number);
const total = arr.reduce((x, y) => x + y, 0);
const avg = total / arr.length || 0;
alert(avg);
}
function AddNumber()
{
document.getElementById('lbl').innerText += `,${document.getElementById('input').value}`;
}
You have a couple of errors in your code. First create the function outside of arr.push(). Second, you should call the function from somewhere for it to work. Also, next time provide the HTML too. You can see a working example here:
let arr = [];
function addNumber() {
const element = document.getElementById("num");
const value = Number.isNaN(Number(element.value)) ? 0 :Number(element.value);
arr.push(value)
printInfo()
}
function printInfo() {
console.log(`The array has ${arr.length} elements.`);
const full = arr.reduce((acc, item) => (acc += item), 0)
const average = full/arr.length
console.log(`The average of the values is ${average}`)
}
<html>
<body>
<button id='main' onclick="addNumber()">
Click me
</button>
<input id="num" type="number"/>
</body>
</html>
I am adding also a minimal working example in fiddle https://jsfiddle.net/5ybz6Lmk/