Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
Javascript Convierta la entrada de Textarea en Array para calcular el total promedio

Estoy tratando de obtener el script para calcular el promedio de los números ingresados en un área de texto. Los números están separados por una coma.

Obtengo un valor de NaN o simplemente no funciona bien.

Este código estuvo más cerca de funcionar realmente. Sin embargo, solo agrega la coma como un elemento nuevo y todos los números se combinan en el primer elemento, dividiendo el número por la cantidad de comas.

 document.querySelector("#input").addEventListener("input", function test() { const strng = document.getElementById("input").value; var arr = strng.split(','); const avg = arr.reduce((a, b) => a + b, 0) / arr.length; document.getElementById("lbl").innerHTML = avg; }); function cycle() { var area = document.getElementById("txt").value; var lines = area.split(','); const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length; document.getElementById("lbl").innerHTML = average([lines]).toFixed(2); } setInterval(cycle, 100)
 <textarea id="input"></textarea> <label id="lbl">Result Here</label> <textarea id="txt"></textarea>

La función cycle() me dio un valor de NaN justo después de ingresar la primera coma en el área de texto.

¿Alguien me puede ayudar?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Cuando divide una cadena de la entrada del usuario, obtiene una matriz de cadenas. Por lo tanto, debe analizar estas cadenas en números y filtrar cualquier valor no numérico antes del cálculo.

 function test() { const inputValue = document.getElementById("input").value; var values = inputValue.split(',').map(v => parseFloat(v)).filter(v => !Number.isNaN(v)); const avg = values.reduce((a, b) => a + b, 0) / values.length; document.getElementById("lbl").innerHTML = (!Number.isNaN(avg)) ? avg : ''; } setInterval(test, 100);
 <textarea id="input"></textarea><br> <label id="lbl">Result Here</label> <textarea id="txt"></textarea>

about 4 years ago · Juan Pablo Isaza Report

0

 // access the DOM elements const inpTxt = document.getElementById("input"); const outTxt = document.getElementById("lbl"); // add event listener to text-area "input" event inpTxt.addEventListener("input", () => { // collect the list of comma separated numbers into an array "numList" const numList = inpTxt .value // access the DOM element "inpTxt"'s value attribute .split(',') // ".split()" using "comma" as the seperator .map(Number) // convert each element into a number .filter( // sanity check to remove any non-number data x => !isNaN(x) ); console.log(numList); // to see in real-time the "numList" array on console if (numList.length) { // if there are any valid numbers in the array outTxt.innerText = ( // change the "label"'s innerText numList.reduce( // sum the numbers in the "numList" array (total, num) => total + num, 0 // initialize the "sum" to zero ) / // divide into "numList.length" to compute average numList.length ); } });
 <div> Type comma-separated numbers in below input box and average will be calculated </div> <div><textarea id="input"></textarea></div> <div><label id="lbl">Result Here</label></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!