斐波那契系列不起作用

时间:2017-11-07 17:10:40

标签: javascript html

此代码返回1,如何解决此问题。我无法解决这个问题..有什么想法吗?

function fibonacci() {
  var i;
  var fib = [];
  fib[0] = 0;
  fib[1] = 1;
  for (i = 2; i <= 10; i++) {
    fib[i] = fib[i - 2] + fib[i - 1];
    return (fib[i]);
  }
}

alert(fibonacci());

4 个答案:

答案 0 :(得分:1)

此外,您可以最小化代码并执行以下操作:

function fibonacci() {
  for (var n = [0, 1], r = 2; r <= 10; r++)
    n[r] = n[r - 2] + n[r - 1];
  return n
}

console.log(fibonacci());

答案 1 :(得分:0)

移出你的回报并返回数组

function fibonacci() {
  var i;
  var fib = []; 
  fib[0] = 0;
  fib[1] = 1;
  
  for (i = 2; i <= 10; i++) {
    fib[i] = fib[i - 2] + fib[i - 1];
  }
  return fib;
}

alert(fibonacci());

答案 2 :(得分:0)

function fibonacci() {
    var i;
    var fib = [];
    fib[0] = 0;
    fib[1] = 1;
    for (i = 2; i <= 10; i++) {
        fib[i] = fib[i - 2] + fib[i - 1];
    }
    return (fib);
}
alert(fibonacci());

答案 3 :(得分:-1)

你想确保你不从循环内的函数返回。将返回线移到循环外但仍在函数内。

&#13;
&#13;
function fibonacci() {
                var i;
                var fib = []; 
                fib[0] = 0;
                fib[1] = 1;
                for (i = 2; i <= 10; i++) {
                    fib[i] = fib[i - 2] + fib[i - 1];
                }
                return fib;
}

alert(fibonacci());
&#13;
&#13;
&#13;