【问题标题】:Stop $.each method when desired variable found [duplicate]找到所需变量时停止 $.each 方法[重复]
【发布时间】:2014-03-12 00:48:33
【问题描述】:

我有一个 $.each 方法,它通过 JSON 搜索来查找变量,我正在使用以下代码:

$.each(heroes_json.heroes, function(key, val){
    if(val.id == hero){
        hero = val.localized_name;
        console.log("Hero name is "+hero);
        return;
    }
    else{
        console.log("Wrong hero, skipping...");   
    }        
});

但问题是我在控制台日志中得到了这个:

所以据我了解,如前所述,$.each 方法会遍历 JSON 中的每个对象。如何做到这一点,以便在找到所需的变量(在本例中为 hero)时,它会停止 each 方法?我假设这是出于性能目的而需要的?

【问题讨论】:

  • 这里有一个类似的问题stackoverflow.com/questions/1784780/…
  • @codingstill 对不起。我没有找到它,因为我搜索了“停止每种方法”之类的东西。我对所有名称感到困惑:方法函数循环中断等。

标签: jquery json


【解决方案1】:

您需要从每个处理程序方法中返回 false 以停止循环的进一步处理

$.each(heroes_json.heroes, function (key, val) {
    if (val.id == hero) {
        hero = val.localized_name;
        console.log("Hero name is " + hero);
        //return false to stop the loop
        return false;
    } else {
        console.log("Wrong hero, skipping...");
    }
});

jQuery.each()

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

【讨论】:

    【解决方案2】:

    你必须返回false才能突破each()

    if (val.id == hero) {
        hero = val.localized_name;
        console.log("Hero name is " + hero);
        return false;
    }
    

    普通的return; 相当于返回undefined,在这种情况下each() 循环将继续。

    【讨论】:

      【解决方案3】:

      您需要返回 false 才能打破循环。因此,在您的实例中,您将需要:

      console.log("Hero name is " + hero);
      return false; //this is instead of using return;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 2011-05-07
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多