views:

99

answers:

3
$.each(3,function(i){
    alert(i)
    })

alert 0,1,2

how to do this using jquery?

thanks

+3  A: 

$.each iterates over an array or object, so you'd want to make an array...

$.each([0,1,2],function(i){alert(i);});

Edit: If you want a function to make the array for you, up to a maximum number, here's one way:

max=5;

$.each(
  (function(){ i=0,f=[]; while(i<max){ f.push(i);i++; } return f;})(),
  function(i){ alert(i); }
  );
Alex JL
+6  A: 

Is this question for another type of example? If not, why not just use a plain old boring javascript loop?

for( var i=0; i<3; i++ ) {
    alert(i);
}

What have I missed?

BenB
+1  A: 

How about you define your own each:

jQuery.extend({
    eachIter: function(to,callback){
        for(var i=0;i<to;i++){
            callback(i);
        }
    }
});

Then you can call it as you said:

$.eachIter(3,function(i){alert(i);});
cmptrgeekken
You should pass the `i` variable to the callback, not the `to` variable, otherwise it will alert 3, three times.
CMS