I have the following loop that I use several times:
    for(var i = 0; i < $options.length; i++) { //...
Rather than repeat myself with that code everytime I want to use that loop, I'd like to turn that into a function.
I've tried the following but get an error "i is undefined"
function optionLoop( $options, callback) {
    for(var i = 0; i < $options.length; i++) {
        callback();
    }
}
Usage:
    optionLoop($options, function(){
         // Do it
    });
But that isn't working. How can I turn a loop into a reusable function to which I can pass another function? And one more question... am I crazy for wanting to do this?
thanks!
You should pass the loop values into your callback:
function optionLoop( $options, callback) {
    for(var i = 0; i < $options.length; i++) {
        callback(i, $options[i]);
    }
}
Then, when you call it, use them in your callback function:
optionLoop($options, function(index, value) {
});
Here's the fiddle: http://jsfiddle.net/vGHK5/
Update: if you want to be able to break out of the loop from within the function, use this:
function optionLoop( $options, callback) {
    for(var i = 0; i < $options.length; i++) {
        if ( callback(i, $options[i]) === false ) break;
    }
}
Then just return false if you want to break.
Here's the fiddle: http://jsfiddle.net/vGHK5/1/
are you trying to access i in the callback? you might want to pass that to callback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With