JavaScript中的函数递归方法?不好的做法? [英] Functional recursive method in JavaScript? Bad practise?
问题描述
Can anyone see a problem with a recursive function written like this:
var recurse = 100;
var recursed = 0;
(function (callback){
callback(callback);
})(function(callback){
recursed++;
console.log('recursed ' + recursed + ' times');
if(recursed < recurse){
callback(callback);
}
});
有什么理由可能会执行速度较慢?或者可能被认为是不好的做法?
Is there any reason why this might execute slower? Or might be considered bad practise?
这个函数式编程已经过时了吗?
Is this functional programming gone AWOL?
推荐答案
是否有任何理由为什么这可能会执行得更慢?
Is there any reason why this might execute slower?
是的。 JavaScript很难调优优化。一个循环会更快。
Yes. JavaScript is hardly tail-call-optimized. A loop would be faster.
或者可能被认为是不好的做法?
Or might be considered bad practise?
是的。你的示例代码是不可读的,很难掌握所有这些回调
的功能。
Yes. Your example code is unreadable, it's hard to grasp what all these callback
s do.
如果你想使用像这样的递归,IENFE(命名& $ / $ / $ / $ / $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b
If you want to use recursion for something like this, an IENFE (Named & Immediately Executed Function Expression) would be a better choice:
(function callback(recursed) {
console.log('recursed ' + recursed + ' times');
if (recursed < 100)
callback(recursed + 1);
})(0);
这篇关于JavaScript中的函数递归方法?不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!