单击按钮以获取前12个斐波纳契数的总和

时间:2015-03-17 16:32:34

标签: javascript fibonacci

我想获得并添加前12个甚至斐波纳契数字,并在我点击按钮时显示在我的页面上。现在我的代码获取并添加偶数。如何将其限制为前12个偶数?

提前谢谢你。 http://jsfiddle.net/lakenney/oryygn4y/

    // first we get the HTML for the button
var getFibSum = document.getElementById("sumFib");

//then we set the event handler for when the button is clicked
getFibSum.onclick = function(){
               document.getElementById("sumFibResult").innerHTML = twelveEvenFibonacciSum();
 }

 /*
  *  twelveEvenFibonacciSum - calulates the sum of the first 12 even fibonacci numbers, with 0, 1 being the first two numbers of the sequence
  */

    function twelveEvenFibonacciSum(){
     /// WRITE YOUR CODE HERE
        // Loop that generates Fibonacci numbers. 
        console.clear();

        var fib = [0, 1]; //Initialize array
        var sum = 0;

        for (var i= 2; i <= 50; i++) {
            fib[i] = fib[i-1] + fib[i-2];    
            var integer = fib[i];
            if(integer  % 2 == 0) {
                 // console.log("my current even fib is " + fib[i]);
                 var sumFibResult = sum += fib[i];
                console.log("my current even fib added to sum " + sumFibResult);
            }
            // Loop until we have 12 even numbers

            }

        //console.log(fib);
       return sumFibResult;
 }

1 个答案:

答案 0 :(得分:0)

向外部作用域添加一个变量,每次调用函数时该变量都会递增。当它等于12时返回。

    for (var i= 2; i <= 50; i++) {
        fib[i] = fib[i-1] + fib[i-2];    
        var integer = fib[i];
        if(integer  % 2 == 0) {
             // console.log("my current even fib is " + fib[i]);
             var sumFibResult = sum += fib[i];
            console.log("my current even fib added to sum " + sumFibResult);
            timesIncremented++;
        }
        // Loop until we have 12 even numbers
        if(timesIncremented >= 12) {
            return;
        }
    }