繁体   English   中英

如何检查foreach函数中的条件是否与Javascript匹配?

[英]How to check if a condition in foreach function matched in Javascript?

我有一个Javascript函数。 我检查数组中每个元素的条件,如果有匹配项,则停止循环。 例如:

var myarray = [5,6,7,8,9,10];
myarray.forEach(function(element){
  if(element == 8)
    break;
});

//myother functions here..

到目前为止一切都还好。 但是在打破循环之后,我的其他功能继续运行。

如果在foreach函数中发生匹配,我不想继续下一个函数,如果没有匹配项可以继续。

我怎样才能做到这一点?

例如,您可以使用(没有功能的版本)

var myarray = [5,6,7,8,9,10];
var found = false;
myarray.forEach(function(element){
  if(element == 8)
    found = true;
});

if (!found) {
  //myother functions here..
}

或者,如果您只是在寻找一个元素

if (myarray.indexOf(8) == -1) {
  //myother functions here..
}

暂无
暂无

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

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