如何打破 javascript 中的 foreach 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45967113/
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
How to break foreach loop in javascript?
提问by Rohit Kumar
I have an object mobile_specswhich have several fields such as DeviceName, Brand, Camera. I loop though the mobile_specsobject so that i can print the specifications of two mobiles in tabular format:
我有一个对象mobile_specs,它有几个字段,例如 DeviceName、Brand、Camera。我循环遍历mobile_specs对象,以便我可以以表格格式打印两个手机的规格:
var i=0;
Object.keys(mobile_specs).forEach(function(key) {
if(i==5)
{
break;
}
var mobile1=mobile_specs.[key];
var mobile2=mobile_specs.[key];
alert(mobile1 + " " +mobile2);
i++;
});
But the above code give me an error which is:
但是上面的代码给了我一个错误:
Illegal break statement
How can i break my loop when i==5 ?
当 i==5 时如何打破循环?
Any help is appreciated.
任何帮助表示赞赏。
回答by marvel308
There is no way to stop or break a forEach()loop other than by throwing an exception. I think forEachis not suited for your job, use a simple loop instead
forEach()除了抛出异常之外,没有其他方法可以停止或中断循环。我认为forEach不适合您的工作,请改用简单的循环

