views:

2798

answers:

4

I'm trying to iterate through an array of elements. jQuery's documentation says:

jquery.Each() documentation

Returning non-false is the same as a continue statement in a for loop, it will skip immediately to the next iteration.

I've tried calling 'return non-false;' and 'non-false;' (sans return) neither of which skip to the next iteration. Instead, they break the loop. What am i missing?

+12  A: 

What they mean by non-false is:

return true;

So this code:

var arr = [ "one", "two", "three", "four", "five" ];
$.each(arr, function(i) {
    if(arr[i] == 'three') {
        return true;
    }
    alert(arr[i]);
});

Will alert one, two, four, five

Paolo Bergantino
+6  A: 

By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return true, 1, 'non-false', or whatever else you can think up.

tj111
+1 for `return 'non-false';`
J Cooper
+1  A: 

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

The Javascript language

Javascript - The Good Parts

mlennox
A: 

How would I return premateruly from the jQuery.each([1,2,3], function(i, v) { ... } ) ?

Moe
Using `return false;` at any stage in the `.each()` iteration will break out of the loop completely.
Jimbo