Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a loop as a function to reuse

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!

like image 976
HandiworkNYC.com Avatar asked Aug 27 '12 01:08

HandiworkNYC.com


2 Answers

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/

like image 82
Joseph Silber Avatar answered Sep 20 '22 15:09

Joseph Silber


are you trying to access i in the callback? you might want to pass that to callback

like image 43
Daniel A. White Avatar answered Sep 21 '22 15:09

Daniel A. White