<script>
//需求:獲取斐波那契數列的前n項陣列
function fib(num) {
var arr = [];
if(num == 1){
return arr = [1];
}else if(num == 2){
return arr = [1,1];
}else{
arr = [1,1];
var a=1;
var b=1;
var c=2;
var arrlen =arr.length;
for(var i=2;i<num;i++){
arr.push(c);
a=b;
b=c;
c=a+b;
}
return arr;
alert( fib(1)); // 1
alert( fib(2)); // 1,1
alert( fib(3)); // 1,1,2
alert( fib(4)); // 1,1,2,3
alert( fib(5)); // 1,1,2,3,5
alert( fib(8)); // 1,1,2,3,5,8,13,21
</script>
<script>
//需求:獲取斐波那契數列的前n項陣列
function fib(num) {
var arr = [];
if(num == 1){
return arr = [1];
}else if(num == 2){
return arr = [1,1];
}else{
arr = [1,1];
var a=1;
var b=1;
var c=2;
var arrlen =arr.length;
for(var i=2;i<num;i++){
arr.push(c);
a=b;
b=c;
c=a+b;
}
return arr;
}
}
alert( fib(1)); // 1
alert( fib(2)); // 1,1
alert( fib(3)); // 1,1,2
alert( fib(4)); // 1,1,2,3
alert( fib(5)); // 1,1,2,3,5
alert( fib(8)); // 1,1,2,3,5,8,13,21
</script>