Jquery every - 停止循环并返回对象
谁能告诉我为什么循环在 5
条目之后没有停止?
http://jsbin.com/ucuqot/edit#preview
$(document).ready(function()
{
someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';
var test = findXX('o322');
});
function findXX(word)
{
$.each(someArray, function(i)
{
$('body').append('-> '+i+'<br />');
if(someArray[i] == 'someArray')
{
return someArray[i]; //<--- did not stop the loop!
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为当您在
each
循环中使用return
语句时,“非 false”值将充当continue
,而false
将充当中断
。您需要从each
函数返回false
。像这样的东西:来自 docs:
Because when you use a
return
statement inside aneach
loop, a "non-false" value will act as acontinue
, whereasfalse
will act as abreak
. You will need to returnfalse
from theeach
function. Something like this:From the docs:
修改后的
$.each
函数它将在非假/非空结果上中断循环并将其返回,所以在你的情况下它将是
modified
$.each
functionit will break loop on non-false/non-empty result and return it back, so in your case it would be
这里:
http://jsbin.com/ucuqot/3/edit
here :
http://jsbin.com/ucuqot/3/edit
试试这个...
Try this ...
来自 http://api.jquery.com/jquery.each/
是的,这很旧,但是,只是为了回答这个问题,这可以更简单一些:
多一点评论:
注意:数组
.includes()
可能更适合这里 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes或者只是
.find()
获取 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findfrom http://api.jquery.com/jquery.each/
Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:
A bit more with comments:
NOTE: array
.includes()
may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includesOr just
.find()
to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find使用 JavaScript 的 Array.prototype.find 来查找数组中的匹配项可能比设置标志更优雅。一旦回调返回真值,循环就会结束,迭代期间的数组值将是
.find
调用的返回值:Rather than setting a flag, it could be more elegant to use JavaScript's
Array.prototype.find
to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the.find
call's return value: