# Why the sum of the numbers in this array to NaN?

Is the task code that asks the user for a number. The program ends input as soon as the visitor enters an empty string, not a number or hit "Cancel".
These numbers need to be saved in the array and as a Supplement at the end to calculate the sum of all numbers.
Everything seems to have done converts numbers entered from string to number, but still the sum of their NaN. Why, because in the array of numerical values?
``````arr = new Array();
var sum = 0;
while(true) {
var number = prompt("Enter a number", 0);
if (number == null || number == "" || !isFinite(number)) {
break;
} else {
arr.push(+number);
sum += arr[number];
}
}
console.log(sum)``````
June 10th 19 at 16:37
June 10th 19 at 16:39
Solution
arr[number] appeal to the element with index number. Replace sum += +number;
June 10th 19 at 16:41
Good evening.
Here is a slightly tweaked Your code, not perfect, but it seems to work.
``````arr = new Array();
var sum = 0;
var i = 0;
while(true) {
var number = prompt("Enter a number", 0);
if (number == null || number == "" || !isFinite(number)) {
break;
} else {
arr.push(+number);
sum += arr[i];
}
i++;
}
console.log(sum)``````
Why drag in the code index if you can use a variable number? It is like to go for a ladder to climb the fence, near the open gate. - Lenny.Botsfo commented on June 10th 19 at 16:44
June 10th 19 at 16:43
Something tweaked that was given when adding three numbers amount, not a string. You have a string

https://jsfiddle.net/c2z1wpyL/

Find more questions by tags JavaScript