日期:2014-05-16 浏览次数:20446 次
function fun2(x) {
if(isFinite(x) && x>0 && x==Math.round(x)) {
if(!(x in fun2)) //如果没有混成结果
fun2[x] = x*fun2(x-1) //计算结果并缓存
return fun2[x]; //返回缓存结果
}
else return NaN;
}
fun2[1] = 1;
console.log(fun2(3)); //6,火狐下测试的,fun2是计算阶乘的
function fun2(x) {
if(isFinite(x) && x>0 && x==Math.round(x)) {
if(!(x in fun2)) //如果没有混成结果
{
fun2[x] = x*fun2(x-1) //计算结果并缓存
console.log('fun2['+x+'] = '+fun2[x]) //递归
}
return fun2[x]; //返回缓存结果
}
else return NaN;
}
fun2[1]=1; //初始化
console.log('第1次算3!:' + fun2(3)); // 递归算 2! 和 3! 并缓存结果
console.log('第2次算3!:' + fun2(3)); // 直接查表 fun2[3]
console.log('第1次算5!:' + fun2(5)); // 递归算 4! 和 5!
// 适合频繁调用该函数的场合,每个新值求1次缓存,最终演变为查表法。
fun2.myName = 'abc'
alert(fun2['myName']==fun2.myName) // 两种访问属性的方式
// []存取的属性名可以是非规则的,fun2[1]应该是fun2["1"],但fun2.1非法。
------解决方案--------------------
js 是弱类型语言。
var obj={};
obj.name ="name";
就可以添加属性,非常灵活。也容易出错