I have an array which I want to add its elements but with the algorithm that I have it gives me an error.
var numeros = [1, 2, 3, 4, 5], suma = 0;
forEach (numeros, function(numero){
suma += numero;
});
console.log(suma);
Error: Uncaught ReferenceError: forEach is not defined
What is the correct way to do it?
And how would it be doing a For
for(var i = 0; i <= numeros.length; i++){
numero = numeros[i];
suma += numero;
}
To compare both methods.
you can do it like this:
with reduce:
with array.prototype.forEach :
with for of :
for classic:
Your mistake is that the syntax must be like this
arreglo.forEach()
, that is, the array through the name of the variable that contains it must access.
the method with the dot syntaxforEach()
and then remove the name of the array that you put inside the loop; being that way