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

129
Views
Calcule el valor de una matriz y devuelva el total en otra matriz

Estoy creando un proyecto en el que cuando hago clic en el botón Agregar, agrego el valor ingresado en la primera entrada a una matriz. Después de ingresar tantos valores como sea posible, me gustaría calcular los números en la matriz e ingresarlos en una matriz que contenga el total y mostrarlo en la consola.

Pude obtener los valores de entrada para agregarlos a la matriz, pero no puedo calcularlos después. ¿Puede alguien amablemente decirme cómo puedo hacer?

HTML

 <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="stile.css"> </head> <body> <form> <div> <input type="number" id="importo"> </div> <button type="submit" id="aggiungi">AGGIUNGI</button> <button type="submit" id="calcola">CALCOLA</button> </form> <script src="script.js"></script> </body>

JS

 const aggiungi = document.getElementById("aggiungi") const calcola = document.getElementById("calcola") const importazione = document.getElementById("importo") const spese = [] console.log(importazione, motivazione) aggiungi.onclick = function(e) { e.preventDefault() spese.push(Number(importazione.value)) console.log(importazione.value) console.log(spese) } /* calcola.onclick = function (e) { e.preventDefault() let somma = 0 let conti = [] for (let i=0; i = spese.length; i++) { conti = [somma += spese[i]] console.log(conti) } } */
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puedes usar array.reduce :

El método reduce() ejecuta una función de devolución de llamada "reductora" proporcionada por el usuario en cada elemento de la matriz, en orden, pasando el valor de retorno del cálculo en el elemento anterior. El resultado final de ejecutar el reductor en todos los elementos de la matriz es un valor único.

La primera vez que se ejecuta la devolución de llamada no hay "valor de retorno del cálculo anterior". Si se proporciona, se puede utilizar un valor inicial en su lugar. De lo contrario, el elemento de la matriz en el índice 0 se usa como valor inicial y la iteración comienza desde el siguiente elemento (índice 1 en lugar del índice 0).

 const aggiungi = document.getElementById("aggiungi") const calcola = document.getElementById("calcola") const importazione = document.getElementById("importo") const spese = [] console.log(importazione); aggiungi.addEventListener("click", e => { spese.push(Number(importazione.value)) console.log(importazione.value) console.log(spese) }); calcola.addEventListener("click", () => { const result = spese.reduce((previousValue, currentValue) => previousValue + currentValue, 0); console.log(result); });
 <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="stile.css"> </head> <body> <form> <div> <input type="number" id="importo"> </div> <button type="button" id="aggiungi">AGGIUNGI</button> <button type="button" id="calcola">CALCOLA</button> </form> <script src="script.js"></script> </body> </html>

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!