arguments.callee 使用
使用辗转反侧法计算两个数的最大公约数时,有一个代码是这样的
function gcd(a, b) {
if (a % b === 0) {
return b;
}
return arguments.callee(b, a % b);
}
console.log(gcd(28, 12)); // 4
console.log(gcd(7890, 123456)); // 6
console.log(gcd(5, 13)); // 1 (公约数为1说明两数互质)
其中 arguments.callee 不会经常使用,查询资料如下:
Arguments 表示函数的参数。arguments 有一个属性 cellee 表示函数参数的指针(指向当前的函数)那么这样写相当于递归调用函数。
我们使用这个优化一下斐波那契函数:
下面是原函数
function factorial(num){
if (num <=1) {
return 1;
} else {
return num * factorial(num-1)
}
}
后面是转换后的函数
function factorial(num){
if (num <=1) {
return 1;
} else {
return num * arguments.callee(num-1);
}
}
使用 argument.callee 的好处:函数内部实现自行递归,不需要获取函数名。如果对外的函数名修改了,不需要改动函数内部的逻辑。