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?
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?
why don't you use normal javascript?
for(var i=0; i<3; i++) {
alert(i);
}
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);
}
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);
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.)