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:
Then, when you call it, use them in your callback function:
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:
Then just return
falseif you want to break.Here’s the fiddle: http://jsfiddle.net/vGHK5/1/