Jquery each – 停止循环并返回对象

前端之家收集整理的这篇文章主要介绍了Jquery each – 停止循环并返回对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
可以有人告诉我为什么循环没有停止后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!
    }   
  });  
}

提前致谢!

解决方法

因为当你在每个循环中使用return语句时,一个“非假”值将作为一个continue,wheras false将作为一个break。您将需要从每个函数返回false。这样的东西:
function findXX(word) {
    var toReturn; 
    $.each(someArray,function(i) {
        $('body').append('-> '+i+'<br />');
        if(someArray[i] == word) {
            toReturn = someArray[i];
            return false;
        }   
    }); 
    return toReturn; 
}

docs

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相关文章