Jquery every - 停止循环并返回对象

发布于 2024-12-17 12:36:29 字数 714 浏览 0 评论 0 原文

谁能告诉我为什么循环在 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!
    }   
  });  
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

回心转意 2024-12-24 12:36:29

因为当您在 each 循环中使用 return 语句时,“非 false”值将充当 continue,而 false 将充当中断。您需要从 each 函数返回 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

我们可以通过使
回调函数返回 false。返回非 false 与 a 相同
for 循环中的 continue 语句;它会立即跳到下一个
迭代。

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

From the 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.

野鹿林 2024-12-24 12:36:29

修改后的 $.each 函数

$.fn.eachReturn = function(arr, callback) {
   var result = null;
   $.each(arr, function(index, value){
       var test = callback(index, value);
       if (test) {
           result = test;
           return false;
       }
   });
   return result ;
}

它将在非假/非空结果上中断循环并将其返回,所以在你的情况下它将是

return $.eachReturn(someArray, function(i){
    ...

modified $.each function

$.fn.eachReturn = function(arr, callback) {
   var result = null;
   $.each(arr, function(index, value){
       var test = callback(index, value);
       if (test) {
           result = test;
           return false;
       }
   });
   return result ;
}

it will break loop on non-false/non-empty result and return it back, so in your case it would be

return $.eachReturn(someArray, function(i){
    ...
沒落の蓅哖 2024-12-24 12:36:29

这里:

http://jsbin.com/ucuqot/3/edit

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

here :

http://jsbin.com/ucuqot/3/edit

function findXX(word)
{  
  $.each(someArray, function(i,n)
  {
    $('body').append('-> '+i+'<br />');
    if(n == word)
    {
      return false;
    }   
  });  
}
烂人 2024-12-24 12:36:29

试试这个...

  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'); 
  console.log(test);



function findXX(word)
{  
  for(var i in someArray){


    if(someArray[i] == word)
    {
      return someArray[i]; //<---  stop the loop!
    }   
  }
}

Try this ...

  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'); 
  console.log(test);



function findXX(word)
{  
  for(var i in someArray){


    if(someArray[i] == word)
    {
      return someArray[i]; //<---  stop the loop!
    }   
  }
}
腹黑女流氓 2024-12-24 12:36:29

“我们可以通过以下方式在特定迭代中打破 $.each() 循环
回调函数返回 false。返回非 false 与
for 循环中的 continue 语句;它会立即跳到
下一次迭代。”

来自 http://api.jquery.com/jquery.each/

是的,这很旧,但是,只是为了回答这个问题,这可以更简单一些:

function findXX(word) {
  $.each(someArray, function(index, value) {
    $('body').append('-> ' + index + ":" + value + '<br />');
    return !(value == word);
  });
}
$(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';
  findXX('o322');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

多一点评论:

function findXX(myA, word) {
  let br = '<br />';//create once
  let myHolder = $("<div />");//get a holder to not hit DOM a lot
  let found = false;//default return
  $.each(myA, function(index, value) {
    found = (value == word);
    myHolder.append('-> ' + index + ":" + value + br);
    return !found;
  });
  $('body').append(myHolder.html());// hit DOM once
  return found;
}
$(function() {
  // no horrid global array, easier array setup;
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];
  // pass the array and the value we want to find, return back a value
  let test = findXX(someArray, 'o322');
  $('body').append("<div>Found:" + test + "</div>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

注意:数组 .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/find

"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."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

function findXX(word) {
  $.each(someArray, function(index, value) {
    $('body').append('-> ' + index + ":" + value + '<br />');
    return !(value == word);
  });
}
$(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';
  findXX('o322');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

A bit more with comments:

function findXX(myA, word) {
  let br = '<br />';//create once
  let myHolder = $("<div />");//get a holder to not hit DOM a lot
  let found = false;//default return
  $.each(myA, function(index, value) {
    found = (value == word);
    myHolder.append('-> ' + index + ":" + value + br);
    return !found;
  });
  $('body').append(myHolder.html());// hit DOM once
  return found;
}
$(function() {
  // no horrid global array, easier array setup;
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];
  // pass the array and the value we want to find, return back a value
  let test = findXX(someArray, 'o322');
  $('body').append("<div>Found:" + test + "</div>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

孤独患者 2024-12-24 12:36:29

使用 JavaScript 的 Array.prototype.find 来查找数组中的匹配项可能比设置标志更优雅。一旦回调返回真值,循环就会结束,迭代期间的数组值将是 .find 调用的返回值:

function findXX(word) {
    return someArray.find((item, i) => {
        $('body').append('-> '+i+'<br />');
        return item === word;
    }); 
}

const 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');
console.log('found word:', test);

function findXX(word) {
  return someArray.find((item, i) => {
    $('body').append('-> ' + i + '<br />');
    return item === word;
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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:

function findXX(word) {
    return someArray.find((item, i) => {
        $('body').append('-> '+i+'<br />');
        return item === word;
    }); 
}

const 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');
console.log('found word:', test);

function findXX(word) {
  return someArray.find((item, i) => {
    $('body').append('-> ' + i + '<br />');
    return item === word;
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文