0

Possible Duplicate:
jQuery each method does not return value

It seems the return statement does not break the loop and return the function. The following code keeps return false....

var __in__ = function(elem, array){
    // $.each(array, function(index, item) {  
   array.forEach(function(index, item) {
        if (item == elem)
            return true;
    });
    return false;
};


console.log(__in__(3,[1,2,3]));
13
  • 2
    You have, essentially, function(){ return true; } in both cases -- it returns from the anonymous function, not from the one that called it! Commented Dec 28, 2012 at 19:43
  • 1
    @Lkahtz How about jQuery.grep() ? Commented Dec 28, 2012 at 19:44
  • 2
    This is probably just an example function, but there's also $.inArray(). Commented Dec 28, 2012 at 19:46
  • 2
    @F.Hauri , please tell me that you are joking. Please !? Commented Dec 28, 2012 at 19:55
  • 2
    @F.Hauri "Better to remain silent and be thought a fool than to speak out and remove all doubt in the end" - Licoln. Of course jQ is Javascript... Commented Dec 28, 2012 at 20:19

3 Answers 3

11

That is because $.each it is executing function callbacks. $.each is not a for loop. The following is what you're after:

var __in__ = function(elem, array){
    var result = false;

    $.each(array, function(index, item) {
        if (item == elem) {
            result = true;
            return false;
        }
    });

    return result;
};

http://jsfiddle.net/unByH/1/

Sign up to request clarification or add additional context in comments.

Comments

4

Your inner return statement only returns from the inner (nested) function, the outer return statement is always running (even on a match).

Comments

3

Try this:

var __in__ = function(elem, array){
    var found = false;

    $.each(array, function(index, item) {
        if (item == elem) {
            found = true;
            return false; // break out of $.each call
        }
    });

    return found;
};

1 Comment

When I started typing there was no complete answer yet. Also, it is not mandatory to return from the each call but I agree that, performance-wise, it should be done, so I'll fix it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.