从Javascript中的switch case内部中断for循环

Break for loop from inside of switch case in Javascript(从Javascript中的switch case内部中断for循环)
本文介绍了从Javascript中的switch case内部中断for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须用什么命令,才能跳出for循环,也是从//code inside直接跳转到//code after

What command I must use, to get out of the for loop, also from //code inside jump direct to //code after

//code before
for(var a in b)
    {
    switch(something)
        {
        case something:
            {
            //code inside
            break;
            }
        }
    }
//code after

推荐答案

不幸的是,Javascript 不允许 break 遍历多个级别.最简单的方法是通过创建匿名函数来利用 return 语句的强大功能:

Unfortunately, Javascript doesn't have allow breaking through multiple levels. The easiest way to do this is to leverage the power of the return statement by creating an anonymous function:

//code before
(function () {
    for (var a in b) {
        switch (something) {
        case something:
            {
                //code inside
                return;
            }
        }
    }
}());
//code after

这是可行的,因为 return 离开了函数,因此隐式地离开了循环,将您直接移动到 code after

This works because return leaves the function and therefore implicitly leaves the loop, moving you straight to code after

正如评论中指出的那样,我上面的答案是不正确的,可以进行多级breaking,如Chubby Boy 的回答,我已投赞成票.

As pointed out in the comments, my above answer is incorrect and it is possible to multi-level breaking, as in Chubby Boy's answer, which I have upvoted.

这是否是明智的,从七年后的角度来看,有点值得怀疑.

Whether this is wise is, from a seven-year-later perspective, somewhat questionable.

这篇关于从Javascript中的switch case内部中断for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)