How to add elements of an array that is a return of another Function in Javascript?

Asked

Viewed 5,000 times

-3

inserir a descrição da imagem aqui

I can’t make that sum, returns Nan, any suggestions? ps: I’m a beginner in JS.

2 answers

2


The error is in the index inside the loop for of the array that is exceeding the number of elements:

            aqui está o erro
                  ↓
for(var i = 0; i <= numbers.length; i++){
    soma += numbers[i];
}

The right thing would be:

for(var i = 0; i < numbers.length; i++){
    soma += numbers[i];
}

As you are beginner, I will list the index of the array:

numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
numbers[5] = 6;
numbers[6] = 7;
numbers[7] = 8;
numbers[8] = 9;
numbers[9] = 10;

The index of arrays always starts with 0, so, to go through the entire array, you need to specify in the loop for that the variable (i=0) smaller than the size length array.

In this case, the array has 10 elements, but the loop for must end in 9 because it starts with 0, that is, from 0 to 9 are 10 loops.

  • Keep coming back Nan :(

  • @Herbertcordeiro Vc wants to add all the values of the array?

  • Yes, all values of the array that returns the range function.

  • @Herbertcordeiro I updated the answer.

  • haha didn’t even realize it man, I started JS these days, just had experience with python and java, thanks!

-1

//somar todos arrays

let teste = [1,2,3,4,5,6,7,8,9]
let soma = 0

for (let i=0; i<teste.length;i++){
    soma += teste[i]
}

console.log(soma)

  • try this one, to see if it’s right

Browser other questions tagged

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