Reputation: 1
If I put this in to codeacademy labs, it returns the sum. But I can't figure out why it won't print/log/return the total when I tell it to.
var a = 0,
b = 1,
f = 1,
fibNums = [];
sum = 0;
while (f < 4000000) {
f = a + b;
if ( f > 4000000 ) {
break;
} else {
a = b;
b = f;
fibNums.push(f);
i ++;
}
}
for (i =0; i < fibNums.length; i++) {
if (fibNums % 2 === 0) {
sum += fibNums(i);
}
}
Upvotes: 0
Views: 35
Reputation: 4757
You have several errors in your code.
You need to access array elements using []
and not ()
. In your case sum is always 0
since you are accessing array in wrong way.
Here is the working code:
var a = 0,
b = 1,
f = 1,
fibNums = [];
sum = 0;
while (f < 4000000) {
f = a + b;
if (f > 4000000) {
break;
} else {
a = b;
b = f;
fibNums.push(f);
}
}
for (var i = 0; i < fibNums.length; i++) {
if (fibNums[i] % 2 == 0) { // access array elements using [] notation
sum += fibNums[i]; // access array using []
}
}
console.log(sum); // Log the sum
console.log(fibNums); //log the fibNums array
Upvotes: 1