繁体   English   中英

如何突破.each()并返回函数的值

[英]How to break out of .each() and return a value for a function

我想使用return false打破.each()但同时返回一个值。 我怎样才能做到这一点?

请参考解决方法以查看我要执行的操作:

function HasStores(state) {
    var statehasstores = false;

    $(stores).each(function (index, store) {
        if (state == store.state && store.category == "meyers") {
            statehasstores = true;
            return false;  // break
        }
    });

    return statehasstores;
}

在伪代码中我喜欢做的是:

Function () {
    for() {
        if found {
            return true;
        }   
    }
    return false;
}

你这样做了......

来自http://api.jquery.com/each/的报价

“我们可以通过返回false来停止回调函数中的循环。”

要有创意:

try {
  $(stores).each(function (index, store) {
    if(state == store.state && store.category == "meyers"){
      throw store;
    }
  });
}
catch(e) {
  // you got e with the value
}

不,我只是在开玩笑,不要用这个:)。 这是我喜欢分享的想法。

在循环外部使用变量来获取值并在之后使用它。

var value;

$(stores).each(function (index, store) {
    if(state == store.state && store.category == "meyers"){
        statehasstores = true;
        value = store; // added line
        return false; //break
    }
});

alert(value);

你做的方式很好。 我在jsFiddle上测试过,请看这里的一个例子

它不适合你吗? 你能展示更多背景吗?

或者,您可以使用for循环而不是each() ,并返回值。

您的建议是如何做到这一点。 我认为它不是一种解决方法,而是一种习惯用语。

好吧,我想对这一点有点怀疑所以也许我在这里说得更清楚了:

  • 当jquery doc说:“我们可以通过返回false来停止回调函数中的循环。” 你也是 :

    Function(){for(){if found {return true; }
    } return false; }

这并不意味着当找到搜索到的元素时,您的函数将返回true。 相反,它总是返回false。

因此,为了使您的功能正常工作,我建议您这样做:

Function () {
   variable found = false;
foreach() {
    if found {
        found = true;
        return false; // This statement doesn't make your function return false but just cut the loop
    }   
}
return found;

}

当然还有很多其他方法可以执行此操作,但我认为这是最简单的方法。

Coopa - 简单!

怎么样:

$.each( myObj, function( key, value ){
  ...
  if( sthg... ){
    myObj.somethingWentHorriblyWrong = true;
    return false;
  }
});

if( myObj.somethingWentHorriblyWrong ){
  // ... do something, not forgetting to go:
  delete myObj.somethingWentHorriblyWrong;
}

PS我最初对$.each(...实际返回)感兴趣。正如它在相关JQ页面上所说,“该方法返回其第一个参数,即迭代的对象”,但事实上解决方案甚至没有要求你使用那个事实......

PPS需要一个返回值的函数吗? 当然包裹在外部功能中。

正如其他人从jQuery Each中注意到的那样,返回false只会从循环中断开而不返回值,返回true然而将“继续”并立即开始下一次迭代。 有了这些知识,您可以在某种程度上简化代码,如下所示:

function HasStores(state) {
  var statehasstores = false;

  $(stores).each(function (index, store){

    // continue or break;
    statehasstores = !(state == store.state && store.category == "meyers"))
    return statehasstores;
  });

  return !statehasstores;
}

这当然是使用双重否定有点愚蠢,并且具有为每个错误迭代保存'true'到statehasstores的副作用,反之亦然,但是最终结果应该是相同的并且您不再具有if语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM