The program receives values and inserts them into an array until it receives a negative value, when it does, it must return the sum of the array, now when it does, it only returns the concatenated values, do you know why???
var arreglo = [];
function suma(arreglo){
let suma = 0;
arreglo.forEach(function(numero){
suma += numero;
});
document.write(suma);
};
do{
var valida = true;
var inserta = prompt('Inserta un numero');
if(inserta < 0){
valida = false;
// Obtenos la suma del arreglo
suma(arreglo);
}else{
arreglo.unshift(inserta);
};
}while(valida == true);
Good day,
Your variable
inserta
receives astring
. In JavaScript you can concatenatestring
using the operator+
so when you do yoursuma()
you concatenate thestring
You must make the value it receives
inserta
numeric, you can do it in the following way:The working code is below:
The "prompt" method returns a string and not a number, so before adding it to your array you must convert it to a number, you can use parseInt.
Greetings.