tags:

views:

30

answers:

4

I have a jQuery variable like this:

var variable = $j(this).val();

Where $j(this) is the "numeric" value of a select option.

What I want to do is loop through the variable value i.e do something once,twice etc, based on the value of the variable. A bit like this:

$j.each(variable, function() {
   do something
});

But it does not do it, which bit is wrong?

Thanks in advance

+2  A: 

Use a for loop instead

for (i = 0; i < variable; i++)
{
    // do something 
}

jQuery's each is for looping through a collection (objects or arrays).

Marko
This performs an action `variable + 1` times.
strager
+2  A: 
for ( var i = 0; i< variable; i++ ) { } 

Assuming variable is something like 5.

meder
Remember that `i` is still global to the function; it is not scoped to the block!
strager
A: 
$(’selector’).each(function(index){
// Your code
});
sanders
A: 

jQuery iterates over a collection; it does not know how to handle "iterating" over a Number.

Instead, you can try a classic for loop:

var variable = $j(this).val(), i;

for (i = 0; i < variable; ++i) {
    // do something
}

If you still want to handle the jQuery-like syntax, you could extend $j.each:

(function ($) {
    var oldEach = $.each;

    $.each = function (index, func) {
        var i;

        if (typeof index === 'number') {
            for (i = 0; i < index; ++i) {
                func.call(null, i);
            }
        } else {
            oldEach.apply(this, arguments);
        }
    };
})($j);
strager
Over-complicating a simple problem?
Marko
@Marko Ivanovski, Not really. I guess jQuery is "over-complicating a simple problem" by having `$.each` in the first place, huh?
strager