function calculateFibonacci(num){ ////算法主体,学习算法的朋友可以自己画画,fibonacci在自然规律中无处不在 return (num === 0 || num === 1) ? num : (arguments.callee(num - 1) + arguments.callee(num - 2)); } function doStuff(num, successCallback, errorCallback){ //主体函数 try{ var results = []; for(var i = 0; i < num - 1; i++){ var result = calculateFibonacci(i); results.push(result); console.log(result); } console.log("Calculate finished!"); if(typeof successCallback === "function"){ successCallback(results.join(", ")); } }catch(ex){ typeof errorCallback === "function" && errorCallback(ex.message); } }
doStuff(5, function(result){ //successCallback function console.log("this is result: " + result); }, function(error){ //errorCallback console.log("Something bad happened: " + error); });
整个过程相对简单,这里就不解释了。主要是fibonacci数列本身有趣 —— 黄金分割点。