Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
JavaScript arrays with functions

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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}`;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda