简体   繁体   English

项目Euler JavaScript#2无法弄清楚如何打印全部内容

[英]Project Euler JavaScript #2 Can't figure out how to print the total

If I put this in to codeacademy labs, it returns the sum. 如果我将其放入Codeacademy实验室,它将返回总和。 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);
    }
}

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. 在您的情况下,总和始终为0因为您以错误的方式访问数组。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM