function sumFibs(num) {
if(num<2) return 1;
//initialize an array with the first two numbers;
var arr = [1,1];
//generate the array with While loop
while((arr[arr.length-1] + arr[arr.length-2])<=num){
arr.push((arr[arr.length-1] + arr[arr.length-2]));
}
//return sum of odd numbers within the array
return arr.filter((num) => num%2!=0).reduce((a,b) => a+b, 0);
}
//test
sumFibs(4);
[JavaScript] 小练习 生成斐波那契数列
猜你喜欢
转载自blog.csdn.net/windgod1992/article/details/81364556
今日推荐
周排行