w调用函数次数的计算。
JavaScript: The Good Parts
<script>
var w = 0;
var w0 =0;
var w10 =0;
var fibonacci = function (n) {
w++
console.log(n)
if(n==0)w0++
if(n==10)w10++
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
};
for (var i = 0; i <= 10; i += 1) {
document.writeln('// ' + i + ': ' + fibonacci(i));
}
console.log(w)
console.log(w0)
console.log(w10)
</script>
0 1
1 1
2 1 1 2 1+2=3
3 2 1 3 1+4=5
4 3 2 5 1+8=9
5 5 3 8 1+14=15
6 8 5 13 1+24=25
7 13 8 21 1+40=41
8 21 13 34 1+66=67
9 34 21 55 1+108=109
10 55 34 89 1+176=177
453
<script type="text/javascript"> <!-- var w = function(n){ return n<2 ? 1 : w(n-1)+w(n-2) } //--> </script>
4.15. Memoization
Functions can use objects to remember the results of previous operations, making it possible to avoid unnecessary work. This optimization is called memoization. JavaScript's objects and arrays are very convenient for this.
Let's say we want a recursive function to compute Fibonacci numbers. A Fibonacci number is the sum of the two previous Fibonacci numbers. The first two are 0 and 1:
var fibonacci = function (n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); }; for (var i = 0; i <= 10; i += 1) { document.writeln('// ' + i + ': ' + fibonacci(i)); } // 0: 0 // 1: 1 // 2: 1 // 3: 2 // 4: 3 // 5: 5 // 6: 8 // 7: 13 // 8: 21 // 9: 34 // 10: 55