This is a regular for loop:
for (var i = 0; i < n; i++) { ... }
It is used to iterate over arrays, but also to repeat a process n times.
I use the above form, but it pushes me away. Header var i = 0; i < n; i++ var i = 0; i < n; i++ var i = 0; i < n; i++ is simple ugly and needs 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) { ... });
Here we use the repeat function, which takes two arguments:
1. number of iterations,
2. a function that is a process that is repeated.
"code-behind" would look like this:
function repeat(n, f) { for (var i = 0; i < n; i++) { f(i); } }
(I know the performance implications of having two additional βlevelsβ in the process scope chain)
BTW, for those of you who use the jQuery library, the above functionality can be obtained from the box using the $.each method, for example:
$.each(Array(n), function(i) { ... });
And what do you think? Is this repeat function a valid alternative for a native loop? What are the downsides of this alternative (besides performance - I know about that)?
Native:
for (var i = 0; i < 10; i++) {
Alternative:
repeat(10, function(i) {
javascript jquery loops
Ε ime Vidas
source share