javascript 条件为真时停止函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23582927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:08:43  来源:igfitidea点击:

Stop function if condition is true

javascriptjquery

提问by John Smith

I use the Array map()Method to check each element in an Array and if the condition in the if clausel is true i call another function.

我使用数组map()方法检查数组中的每个元素,如果 if 子句中的条件为真,我将调用另一个函数。

$.map(data['icd'], function (field, i) {
   if(field.nummer == search){
      Diagnose.single(field.id);
   };
});

Now my problem is that i want to stop the mapmethod if a element fullfills the if condition. Because i noticed that when i have for example 6 elements that fullfill the condition the function Diagnose.single(field.id);is called 6 times instead of once!

现在我的问题是,map如果元素满足 if 条件,我想停止该方法。因为我注意到当我有例如 6 个元素满足条件时,该函数Diagnose.single(field.id);被调用 6 次而不是一次!

I tried:

我试过:

$.map(data['icd'], function (field, i) {
   if(field.nummer == search){
      Diagnose.single(field.id);
      return true;
   };
});

But this didnt worked! What can i do instead? Thanks

但这没有用!我可以做什么?谢谢

回答by dfsq

Use simple for-loop with break statement:

使用带有 break 语句的简单 for 循环:

for (var i = 0; i < data['icd'].length; i++) {
   if (data['icd'][i].nummer == search){
      Diagnose.single(data['icd'][i].id);
      break;
   };    
}

mapis used for different tasks.

map用于不同的任务。

回答by PanJ

If you do not need IE8 support, you can use Array.prototype.some

如果不需要IE8支持,可以使用 Array.prototype.some

data['icd'].some(function (field, i) {
   if(field.nummer == search){
      Diagnose.single(field.id);
      return true;
   };
});

回答by ReGdYN

Return false and replace .map with .each

返回 false 并用 .each 替换 .map

$.each(data['icd'], function (field, i) {
   if(field.nummer == search){
      Diagnose.single(field.id);
      // Need to return false, return true will go for a success and still continue.
      return false;
   };
});

回答by Mottie

I think in your case you want to use the jQuery each function. You can then return falseto break out of the loop

我认为在你的情况下你想使用jQuery each 函数。然后你可以return false跳出循环

$.each(data['icd'], function (field, i) {
   if(field.nummer == search){
      Diagnose.single(field.id);
      return false;
   };
});

or even better, use a simple for-loop as @disq shared.

或者甚至更好,使用一个简单的 for 循环作为 @disq 共享。