There are many problems in your code and one of them is that you use the operator in
instead of the operator of
. The in is an operator that will traverse the attributes of an object and not its values.
const objeto = {nome: "lucas", idade: 32};
for (let chave in objeto) {
console.log(chave); // Saída: nome; idade
}
On the other hand, the for. of will scroll through each element of your Array. See below what you were actually traversing with your code:
const valores = [1, 2, 3, 4, 5];
for (let i in valores){
console.log(i);
}
Another problem with your code is that you were not incrementing the variable soma
. Every loop that loops you for
did, you just assigned a value of i + i
, that is, what was happening was this:
soma = 1 + 1;
soma = 2 + 2;
soma = 3 + 3;
// ...
To correct your code, you must use the operator of
to go through the array elements and then you should increment to the variable soma
the value of i
, of that mouth:
const valores = [1, 2, 3, 4, 5];
var soma = 0;
for (let i of valores){
soma += i; // O operador "+=" equivale a fazer "soma = soma + 1"
}
console.log(`Soma de ${valores.join(" + ")} = ` + soma);
Besides using the loop for
, you can use the method reduce to go through the elements of the Array and perform some action with them using an auxiliary data that will be modified throughout the process and finally returned.
It became a little difficult to explain ? Then see the method working in practice.
const valores = [1, 2, 3, 4, 5];
// O número 0 na chamada do método é o valor inicial que será manipulado.
var resultado = valores.reduce(function(valor, valores_somados){
return valores_somados + valor;
}, 0);
console.log(resultado);
// É possível também reduzir o código acima utilizando arrow function.
var resultado = valores.reduce((valor, soma) => valor + soma, 0);
console.log(resultado);
sorry for making such a bad topic, it’s the first time I publish here.
– eleven08