admin管理员组

文章数量:1404346

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!

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!

Share Improve this question edited Aug 27, 2012 at 1:15 j08691 208k32 gold badges269 silver badges280 bronze badges asked Aug 27, 2012 at 1:11 HandiworkNYC.HandiworkNYC. 11.1k25 gold badges95 silver badges156 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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/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/vGHK5/1/

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

本文标签: javascriptDefine a loop as a function to reuseStack Overflow