標籤:push set ... on() 斐波那契 obj time 斐波那契數 輸出
一、斐波那契數列:var arr = [1,1,2,3,5,8....];
1.用函數產生斐波那契數列的隨意的任一項;
function fib(n){ if(n<3){ return 1; }else{ return fib(n-1)+fib(n-2); }}
function fib(n){ var n1=1,n2=1,fn=0; for(var i=0;i<n-2;i++){ fn = n1+n2; n1 = n2; n2 = fn; } return n2;}
2.用遞迴的方式產生斐波那契數列;
var arrObj = { arr:[], createO:function(n){ if(n<2){ return 1; }else{ return this.createO(n-1)+this.createO(n-2); } }, arrCreate:function(n){ for(var i=0 ;i<n;i++){ this.arr.push(this.createO(i)); } return this.arr; } }; arrObj.arrCreate(8)
3.在每斐波那契數列的一項的時間間隔內輸出這一項的斐波那契數列的值;
var arrObj = { arr:[], createO:function(n){ if(n<2){ return 1; }else{ return this.createO(n-1)+this.createO(n-2); } }, arrCreate:function(n){ for(var i=0 ;i<n;i++){ var _this = this; var font = this.createO(i); var time = font*1000; (function(i,_this,time){ setTimeout(function(){ console.log(_this.createO(i)); },time); })(i,_this,time); } return this.arr; } }; arrObj.arrCreate(8)
js-setTimeout參數,遞迴