Jquery 每个循环未退出 return 0

Jquery each loop not exiting by return 0

退出 each 循环时 - return 0 不工作。但是,将其更改为 return false 效果很好。

Fiddle here

常规 JavaScript 循环 (while,for) 在 return 0 前正常退出。不破坏统一性吗!

jQuery documentation

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

JSFiddle as example

区别只是 0false 不完全相同。

通常当需要布尔值时,任何值都可以使用,并且它会被转换为布尔值。在这种情况下,0 将转换为 false.

在 jQuery $.each 循环中不起作用。如果您没有从函数中明确 return 任何内容,则 return 值为 undefined。如果将其转换为布尔值,则该布尔值也将变为 false.

$.each 方法不会将 return 值转换为布尔值,它专门查找值 false。任何其他值都会让循环继续。

使用return0,将return零,这是一个数字。使用 return false 表示 return 没有任何内容,或者不 return.

简单地说,0 !== false。

在您自己的代码中,您有时可能会检查类似错误的答案:

0 == false;  // true
null == false;  // true.

但是,jQuery(正确地)使用了严格的相等 (===) 运算符。

因此:

0 === false; // false
null === false;  // false
false === false; // true

如果从根本上说这是一个身份与平等问题: Which equals operator (== vs ===) should be used in JavaScript comparisons?

要打破 $.each 循环,您 在循环回调中 return false

Returning anything else skips to the next iteration, equivalent to a continue in a normal loop.

Refer Document