风和日丽 2019-06-28
递归,函数自己调用自己
function fn(num){ console.log(num) if(num == 0){ return; } fn(num-1) } fn(10)
for循环
function fn(num) { var sum = 0; for (var i = 0; i < num; i++) { if (i % 3 == 0 && i % 5 == 0) { sum += i; } } return sum; } console.log(fn(100))
递归
function fn(num) { if (num > 100) { return 0; } if (num % 15 == 0) { return num + fn(num + 1) } return fn(num + 1) } console.log(fn(1)); // 1 -> fn(1+1) // 2 -> fn(2+1) // ... //15 -> 15+fn(15+1) // 16 -> 15+fn(16+1) // 30 -> 15+fn(30+1); // 31 -> 15+30+fn(31+1) // ... // 15+30+45+60+75+90+fn(100) // 15+30+45+60+75+90+fn(101) => 15+30+45+60+75+90+0
1-10之间,把所有能被2整除的数获到,然后累加求和
function fn(num) { if (num > 10) { return 0; } if (num % 2 == 0) { return num + fn(num + 1) } return fn(num + 1) } console.log(fn(1)); // 1 => fn(1+1) => fn(2) // 2 => 2+fn(2+1) => 2+fn(3) // 3 => 2+fn(3+1) => 2+fn(4) // 4 => 2+4+fn(4+1) => 2+4+fn(5) //.. //10 2+4+6+8+10+fn(11) //11 2+4+6+8+10+0
function fn(num){ if(num<1){ return 1; } if(num%2 ==0){ return num* fn(num-1) } return fn(num-1) } var result = fn(10); console.log(result);