Where is the mistake? I want to sum every number in the array. The alert says NaN
.
var numbers = [10, 42, 5, 87, 61, 34, 99];
var i = 0;
var e = 0;
while(i <= numbers.length) {
e = e + numbers[i];
i++;
}
alert(e);
Where is the mistake? I want to sum every number in the array. The alert says NaN
.
var numbers = [10, 42, 5, 87, 61, 34, 99];
var i = 0;
var e = 0;
while(i <= numbers.length) {
e = e + numbers[i];
i++;
}
alert(e);
Your condition is wrong, just use < insteead of <=
There's a few ways you can improve this. The first is that you want to change your condition to
i < numbers.length
, noti <= numbers.length
. As you've written it, the last number will never be counted.Another way you can improve this is using the
+=
notation -- there's no need to writee = e + numbers[i]
when you can writee += numbers[i]
.Alternatively using the ES2015 syntax you can do it like this.
You can read about
Array.prototype.reduce(accumulator, element, callback, startingValue)
here.You could íterate from the end of the array with a post increment and a check for truthyness in the
while
condition.Inside just add the item.
The problem is in array length You are checking because array index starts with 0. In that way when doing:
You are checking [0: 10, 1: 42, 2: 5, 3: 87, 4: 61, 5: 34, 6: 99, 7:???] because numbers length is 7. To solve it just do:
where You don't check non existing number in array.
Here is how we were thought in school:
The for loop adds this i++ You make in a while loop and makes code a bit more clear.
No need for declaring i in main code :)
Although don't make school break Your creativity, Your code is great! :)
This line is the reason:
Arrays are 0 index so you can go from index 0 (inclusive) until
numbers.length
(exclusive). You are going beyond that limit, causing you to access an element that isn't defined at the given index. You must do this instead: