How To Sum Numbers Saved As Array In Javascript With While Loop
Solution 1:
This line is the reason:
while(i <= numbers.length) {
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:
while(i < numbers.length) {
Solution 2:
Alternatively using the ES2015 syntax you can do it like this.
let numbers = [10, 42, 5, 87, 61, 34, 99];
let sum = numbers.reduce((a,b) => a + b);
You can read about Array.prototype.reduce(accumulator, element, callback, startingValue)
here.
Solution 3:
Your condition is wrong, just use < insteead of <=
while(i < numbers.length)
Solution 4:
There's a few ways you can improve this. The first is that you want to change your condition to i < numbers.length
, not i <= 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 write e = e + numbers[i]
when you can write e += numbers[i]
.
Solution 5:
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.
var numbers = [10, 42, 5, 87, 61, 34, 99],
i = numbers.length,
e = 0;
while (i--) {
e += numbers[i];
}
console.log(e);
Post a Comment for "How To Sum Numbers Saved As Array In Javascript With While Loop"