简体   繁体   中英

How to break out of .each() and return a value for a function

I want to use return false to break a .each() but also return a value at the same time. How can I do this?

Please refer to a work-around function to see what I am trying to do:

function HasStores(state) {
    var statehasstores = false;

    $(stores).each(function (index, store) {
        if (state == store.state && store.category == "meyers") {
            statehasstores = true;
            return false;  // break
        }
    });

    return statehasstores;
}

What Id like to do in pseudo code is:

Function () {
    for() {
        if found {
            return true;
        }   
    }
    return false;
}

You're doing it right...

Quote from http://api.jquery.com/each/

"We can stop the loop from within the callback function by returning false."

Be creative:

try {
  $(stores).each(function (index, store) {
    if(state == store.state && store.category == "meyers"){
      throw store;
    }
  });
}
catch(e) {
  // you got e with the value
}

No, I was just kidding, don't use this :). It came as an idea I liked to share.

Use a variable outside the loop to get the value and use it afterward.

var value;

$(stores).each(function (index, store) {
    if(state == store.state && store.category == "meyers"){
        statehasstores = true;
        value = store; // added line
        return false; //break
    }
});

alert(value);

The way you're doing is just fine. I've tested on jsFiddle, see an example here .

It's not working for you? Can you show more context?

或者,您可以使用for循环而不是each() ,并返回值。

What you're suggesting is the way to do it. I'd think of it less as a workaround and more as an idiom.

Okay I guess there's a little doubt about this point so maybe I'm making it clearer here :

  • When jquery doc says : "We can stop the loop from within the callback function by returning false." and you do :

    Function () { for() { if found { return true; }
    } return false; }

This doesn't mean that you're function will return true when find the searched element. Instead, it will always return false.

So to make your function work as you whish I propose to do so :

Function () {
   variable found = false;
foreach() {
    if found {
        found = true;
        return false; // This statement doesn't make your function return false but just cut the loop
    }   
}
return found;

}

Of course there are many other ways to perform this but I think this is the simplest one.

Coopa - Easy !

How about:

$.each( myObj, function( key, value ){
  ...
  if( sthg... ){
    myObj.somethingWentHorriblyWrong = true;
    return false;
  }
});

if( myObj.somethingWentHorriblyWrong ){
  // ... do something, not forgetting to go:
  delete myObj.somethingWentHorriblyWrong;
}

PS I was initially interested in what $.each(... actually returns. As it says on the relevant JQ page , "The method returns its first argument, the object that was iterated", but in fact the solution doesn't even require that you use that fact...

PPS Need a function that returns a value? Wrap in an outer function of course.

As others have noted from jQuery Each , returning false will only break from the loop not return the value, returning true however will 'continue' and immediately begin the next iteration. With that knowledge, you could somewhat simplify your code like this:

function HasStores(state) {
  var statehasstores = false;

  $(stores).each(function (index, store){

    // continue or break;
    statehasstores = !(state == store.state && store.category == "meyers"))
    return statehasstores;
  });

  return !statehasstores;
}

This of course is a little silly using the double negative, and has the side effect of saving 'true' to statehasstores for every false iteration and vice versa, however the end result should be the same and you no longer have that if statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM