2014-09-24 144 views
2

我就简单的js函数的工作... u能告诉我如何替换递归函数的循环.. 在拨弄下面提供我的代码.. 我想学习JS与递归函数替换for循环

http://jsfiddle.net/utbsgnzu/4/

function operation() { 
    console.log("testing"); 
} 

function repeat(operation, num) { 
    for (var i = 0; i < num; i++) { 
     operation(); 
    } 
} 

//repeat(operation, 10); 
module.exports = repeat 

回答

3
function operation() { 
    console.log("testing"); 
} 

function repeat(operation, num) { 
    if (num === 0) return; 
    operation(); 
    repeat(operation, num-1); 
} 

//repeat(operation, 10); 
module.exports = repeat 
0

循环是自然迭代。递归方法并不适合这种情况。无论如何,在这里你走了。但用它只是为了好玩,从来没有真正:)

function repeat(func,maxruns,run){ 
    if(run>=maxruns){ 
     return; 
    } 
    func(); 
    repeat(func,maxruns,(run||0)+1); 
} 
repeat(operation,10); 
-2
var foo = function foo() { 
console.log(arguments.callee); // logs foo() 
// callee could be used to invoke recursively the foo function (e.g.  arguments.callee()) 
}(); 
</script></body></html> 
+1

你不应该使用[arguments.callee的(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference /函数/参数/被调用者),因为它已被弃用,并且在ES5中不允许再使用它:'[...]警告:第5版ECMAScript(ES5)禁止在严格模式下使用arguments.callee 。避免使用arguments.callee()方法,通过给函数表达式一个名字或者在函数必须调用它自己时使用一个函数声明[...]'' – 2016-08-07 09:43:51