Cómo saltar a la siguiente iteración en jQuery.cada() util?


Estoy tratando de iterar a través de una matriz de elementos. La documentación de jQuery dice:

Jquery.Cada() documentación

Devolver non-false es lo mismo que una instrucción continue en un bucle for, se saltará inmediatamente a la siguiente iteración.

He intentado llamar a 'return non-false;' y 'non-false;' (sin retorno) ninguno de los cuales salta a la siguiente iteración. En cambio, rompen el círculo. ¿Qué me estoy perdiendo?

Author: Josh, 2009-01-27

6 answers

Lo que quieren decir con no-falso es:

return true;

Así que este código:

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

Alertará a uno, dos, cuatro, cinco

 714
Author: Paolo Bergantino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-26 22:16:07

Por 'return non-false', significan devolver cualquier valor que no funcionaría como booleano false. Para que puedas volver true, 1, 'non-false', o cualquier otra cosa que se te ocurra.

 59
Author: tj111,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-26 22:18:50

Javascript tiene la idea de 'verdad' y 'falsedad'. Si una variable tiene un valor entonces, generalmente 9 como verá) tiene 'truthiness' - null, o ningún valor tiende a'falsedad'. Los fragmentos a continuación podrían ayudar:

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

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

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

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

Esperemos que eso ayude?

Además, vale la pena ver estos videos de Douglas Crockford

El lenguaje Javascript

Javascript - Las Partes Buenas

 5
Author: mlennox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-26 23:27:09

No olvides que a veces puedes simplemente caerte del final del bloque para llegar a la siguiente iteración:

$(".row").each( function() {
    if ( ! leaveTheLoop ) {
        ... do stuff here ...
    }
});

En lugar de regresar de esta manera:

$(".row").each( function() {
    if ( leaveTheLoop ) 
        return; //go to next iteration in .each()
    ... do stuff here ...
});
 3
Author: Lee Meador,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-30 16:26:13

El bucle solo se rompe si devuelve literalmente false. Ex:

// this is how jquery calls your function
// notice hard comparison (===) against false
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
   break;
}

Esto significa que puede devolver cualquier otra cosa, incluyendo undefined, que es lo que devuelve si no devuelve nada, por lo que simplemente puede usar una declaración de devolución vacía:

$.each(collection, function (index, item) {
   if (!someTestCondition)
      return; // go to next iteration

   // otherwise do something
});

Es posible que esto pueda variar según la versión; esto es aplicable para jquery 1.12.4. Pero realmente, cuando sales de la parte inferior de la función, también estás devolviendo nada, y es por eso que el bucle continúa, así que esperaría que allí no hay posibilidad alguna de que devolver nada pudiera no continuar el bucle. A menos que quieran forzar a todos a comenzar a devolver algo para mantener el bucle en marcha, devolver nada tiene como una forma de mantenerlo en marcha.

 2
Author: Dave Cousineau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-23 21:44:45

JQuery.noop () puede ayudar

$(".row").each( function() {
    if (skipIteration) {
        $.noop()
    }
    else{doSomething}
});
 -3
Author: melaxom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-22 10:13:08