JavaScript 计算斐波那切数列

斐波那切数列是:1, 1,2,3,5,8,13,21,34......(当前数等于前两个数之和)

这里我们将使用递归函数,递归函数就是函数调用自身的函数。

function feibo(a) {
  for (var i = 1; i <= a; i++){
      if(a == 1 || a == 2) {
        return 1;        
      }
      else  {
        return feibo(a-1) +feibo (a-2);
        }
    }  
}
console.log(feibo(1)); //result: 1
console.log(feibo(2)); //result: 1
console.log(feibo(3)); //result: 2
console.log(feibo(4)); //result: 3
console.log(feibo(5)); //result: 5
console.log(feibo(6)); //result: 8
console.log(feibo(10)); //result: 55

 

转载于:https://www.cnblogs.com/ningxin/p/10108035.html

你可能感兴趣的:(javascript)