JavaScript for循环替代方案:repeat(n,function(i){...}); [英] JavaScript for-loop alternative: repeat(n, function(i) { ... });
问题描述
这是常规的for循环:
This is the regular for-loop:
for (var i = 0; i < n; i++) { ... }
它用于遍历数组,但也只是重复执行某些过程n
次.
It is used to iterate over arrays, but also to just repeat some process n
times.
我使用上述表格,但它使我感到排斥.标头var i = 0; i < n; i++
很丑陋,每次使用时都必须按字面意义进行重写.
I use the above mentioned form, but it repulses me. The header var i = 0; i < n; i++
is plain ugly and has to be rewritten literally every time it is used.
我写这个问题是因为我想出了一个替代方案:
I am writing this question because I came up with an alternative:
repeat(n, function(i) { ... });
这里我们使用repeat
函数,该函数带有两个参数:
1.迭代次数,
2.主体代表正在重复的过程的功能.
Here we use the repeat
function which takes two arguments:
1. the number of iterations,
2. a function which body represents the process that is being repeated.
隐藏代码"如下所示:
function repeat(n, f) {
for (var i = 0; i < n; i++) {
f(i);
}
}
(我知道在流程的范围链中具有两个额外的级别"会对性能产生影响)
(I am aware of the performance implications of having two additional "levels" in the scope chain of the process)
顺便说一句,对于那些使用jQuery库的人来说,上述功能可以通过$.each
方法立即实现,如下所示:
BTW, for those of you who use the jQuery library, the above mentioned functionality can be achieved out-of-the-box via the $.each
method like so:
$.each(Array(n), function(i) { ... });
那您怎么看?此repeat
函数是否是本机for循环的有效替代方法?这种选择的弊端是什么(除了性能-我对此有所了解)?
So what do you think? Is this repeat
function a valid alternative to the native for loop? What are the down-sides of this alternative (other than performance - I know about that)?
母语:
for (var i = 0; i < 10; i++) {
// do stuff
}
替代:
repeat(10, function(i) {
// do stuff
});
推荐答案
这是一个有趣的想法,但是如果您不喜欢该循环的语法,则总是可以执行另一种类型的循环:
it's an interesting thought, but if you dislike the syntax for the loop, you could always do a different type of loop:
var i = arr.length;
while (i--) {
// do stuff
}
相反的while循环通常也比for循环快.
the reverse while loop is generally faster than a for loop as well.
这篇关于JavaScript for循环替代方案:repeat(n,function(i){...});的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!