Jquery each - 停止循环并返回对象 [英] Jquery each - Stop loop and return object

查看:26
本文介绍了Jquery each - 停止循环并返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么循环在 5 条目后没有停止?

Can anybody tell me why the loop did not stop after the 5 entry?

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!
    }   
  });  
}

推荐答案

因为当你在 each 循环中使用 return 语句时,一个非假"值将作为 continue,而 false 将作为 break.您需要从 each 函数返回 false.像这样:

Because when you use a return statement inside an each loop, a "non-false" value will act as a continue, whereas false will act as a break. You will need to return false from the each function. Something like this:

function findXX(word) {
    var toReturn; 
    $.each(someArray, function(i) {
        $('body').append('-> '+i+'<br />');
        if(someArray[i] == word) {
            toReturn = someArray[i];
            return false;
        }   
    }); 
    return toReturn; 
}

来自文档:

我们可以在特定的迭代中打破 $.each() 循环回调函数返回false.返回非假与 a 相同for 循环中的 continue 语句;它会立即跳到下一个迭代.

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.

这篇关于Jquery each - 停止循环并返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆