Salida planificada:
The array has 10 elements. The average of the values is 36.1Planeo dos funciones: addNumber() y printInfo().
Función: addNumber() lee un valor de un campo de entrada de texto en el documento HTML (id="num") y lo agrega al final de la matriz.
Otra función: printInfo() envía la cantidad de elementos en la matriz a la consola, luego el promedio de sus valores.
El documento HTML tiene dos botones para llamar a las funciones.
Escribí:
let arr = []; arr.push (function addNumber() { let element = document.getElementById("num"); }) function printInfo() { console.log (arr.length ); }¿Cómo usar botones para llamar a las funciones en HTML?
¿Cómo contar el promedio de valores en la matriz?
Hola aquí hay un ejemplo de trabajo. https://jsfiddle.net/7t41y80m/
Ejemplo HTML
<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}`; }Tienes un par de errores en tu código. Primero cree la función fuera de arr.push(). En segundo lugar, debe llamar a la función desde algún lugar para que funcione. Además, la próxima vez proporcione el HTML también. Puede ver un ejemplo de trabajo aquí:
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>Estoy agregando también un ejemplo de trabajo mínimo en violín https://jsfiddle.net/5ybz6Lmk/