views:

55

answers:

4

This is my code:

$.each(3, function(n) {
    alert(n);
});

I want to alert three times but it doesn't work. What can I do?

+1  A: 

why don't you use normal javascript?

for(var i=0; i<3; i++) {
  alert(i);
}
Polybos
+1  A: 

You can't.
$.each can only iterate over arrays or objects.

You're looking for the for loop:

for(var n = 0; i < 3; i++) {
    alert(n);
}
SLaks
any other jquery method can do this ??
zjm1126
No. jQuery is not a magic device that eliminates the need for Javascript.
SLaks
Why it has to be jquery's? use plain JS for such a simple task. That's like downloading a 20k plugin to do an alert.
Ben
+4  A: 

each must operate on an object. Try to create an array of length 3, e.g.

$.each(new Array(3),
       function(n){alert(n);}
);

Of course, I don't see the reason to avoid normal Javascript.

for (var n = 0; n < 3; ++ n)
   alert(n);
KennyTM
+1 never thought of that.
SLaks
+1 good answer, @KennyTM, I remember that you've posted a nice image about using jQuery to add two numbers that made me laugh that I cannot find anywhere. Could you please share the link again because it seems that the OP insists on using jQuery instead of a simple loop.
Darin Dimitrov
@Darin: http://www.doxdesk.com/img/updates/20091116-so-large.gif
SLaks
@John: No. The callback's first parameter is the index, not the value. Also, you mean `undefined`, not `0`.
SLaks
@Slaks, oh yeah man, hilarious. Thanks. I will bookmark it for future reference :-)
Darin Dimitrov
@Darin: You can go to [meta](http://meta.stackoverflow.com) and search [jQuery](http://meta.stackoverflow.com/search?q=jQuery). It is in [the first answer of the first question](http://meta.stackoverflow.com/questions/45176/when-is-use-jquery-not-a-valid-answer-to-a-javascript-question/48195#48195).
KennyTM
@KennyTM, thanks, this is really freakin. I think that this question also deserves a place on the daily WTF.
Darin Dimitrov
+1  A: 

Late answer, but another option would be to prototype the Number with a method that would call a callback that many times.

Number.prototype.loop = function(cb) {
    for (var i = 0; i < this; i++) {
        cb.call(this, i);
    }
    return this + 0;
};

Then call it like this:

(3).loop(function(i) {
    alert( i );
});

RightJS does something like this. (Others probably too.)

patrick dw
Out of curiosity, why do you need the `this + 0`?
sdolan
@sdolan - It is a way of coercing the return value type back to a `number` instead of an `object`. Not necessary for the function, but just a quick way to return the value of the Number object.
patrick dw
@patrick dw: Thanks, that's what I was assuming.. just never seen it before.
sdolan