Trying to print the total sum of all values within the list?

Asked

Viewed 50 times

-1

I’m trying to print the total sum of all the values inside the list, but what my code does is add the first element with the first element and give the result, then the second element with the second element and so on. Follows code:

const valor = [1, 2, 3, 4, 5];

for (let i in valor){    
    i++;
    let soma = i + i;
    console.log(`i = ${soma}`);
}
  • sorry for making such a bad topic, it’s the first time I publish here.

2 answers

1

In your question your code has enough problems one of them is to put the soma to print inside the for, at that time the variable soma should only receive the sum of the next item and the soma and out of that for show, another problem is that used the for wrong, in which case it should be the for..of that really takes the value of each position.

Some basic examples:


To sum up elements of a array in Javascript:

Using for

const valor = [1,2,3,4,5];
let soma = 0;
for (let i = 0; i < valor.length; i++){    
    soma = valor[i] + soma;
}

document.getElementById("app").innerHTML = soma;
<div id="app"></div>

Using for. of:

const valor = [1,2,3,4,5];
let soma = 0;
for (let i of valor){    
    soma = soma + i;
}

document.getElementById("app").innerHTML = soma;
<div id="app"></div>

Using reduce:

const valor = [1,2,3,4,5];

const soma = valor.reduce((a,b) => a + b, 0);

document.getElementById("app").innerHTML = soma;
<div id="app"></div>

  • 1

    Thank you very much, you helped too!

0


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);

  • thank you very much, it helped a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.