如何从 javascript 中的 foreach 循环中跳出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39882842/
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-08-23 23:00:54  来源:igfitidea点击:

How to break out from foreach loop in javascript

javascript

提问by Sahil

I am newbie in Javascrript. I have a variable having following details:

我是 Javascrript 的新手。我有一个具有以下详细信息的变量:

var result = false;
[{"a": "1","b": null},{"a": "2","b": 5}].forEach(function(call){
    console.log(call);
    var a = call['a'];
    var b = call['b'];
    if(a == null || b == null){
        result = false
        break;
    }
});

I want to break the loop if there is NULL value for a key. How can I do it?

如果键有 NULL 值,我想中断循环。我该怎么做?

回答by fathy

Do not use .forEach then but for loop:

不要使用 .forEach then 而是 for 循环:

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)

    var a = call['a'], b = call['b']

    if(a == null || b == null) {
        result = false
        break
    }
}