I can not do this sum, returns NaN, any suggestions? ps: I'm a beginner in JS.
The error is in the index within 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 correct one would be:
for(var i = 0; i < numbers.length; i++){
soma += numbers[i];
}
As a beginner, I'll list the array's indexes:
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 must specify in the for
loop that the variable ( i=0
) is less than the length
size of the array. / p>
In this case, the array has 10 elements, but the for
loop must end in 9
because it starts with 0
, that is, 0 to 9 is 10 loops.