简体   繁体   English

如何在 Typescript 中使用 break 语句

[英]How to use break statement in Typescript

I'm new to Javascript.我是 Javascript 的新手。 I started with a very basic project in Angular ie Form validation.我从一个非常基本的 Angular 项目开始,即表单验证。 In my case I've to call my custom method, validationTest() within itself only once.就我而言,我只需要在自身内部调用我的自定义方法validationTest()一次。 If I do not put any break condition then there will be too many recursions.如果我不设置任何中断条件,那么将会有太多的递归。 I have to stop this.我必须阻止这一切。 I tried many other solutions:我尝试了许多其他解决方案:

  1. Break Statement in TypeScript TypeScript 中的 Break 语句
  2. TypeScript - Loops 打字稿 - 循环

I followed them very carefully, but I'm getting this:我非常小心地跟着他们,但我得到了这个:

Module parse failed: Unsyntactic break (84:12)模块解析失败:非语法中断 (84:12)

Here's my code:这是我的代码:

validationTest() {
    let count =0;
    this.isAnyRangeInvalid = false;
    this.monthpicker.forEach(picker => {
        if (picker.isValidRange === false) {
            this.isAnyRangeInvalid = true;
        }
    });
    count ++;
    if(count===1) {
        break;
    }
    this.validationTest();
}

Even VScode editor is also showing a red zig-zag line under the token break .甚至 VScode 编辑器也在 token break下显示了一条红色的锯齿线。 I'm coming from Java and CPP background.我来自 Java 和 CPP 背景。 Please correct me.请纠正我。

To stop a function from executing, use return .要停止执行函数,请使用return break only makes sense in the context of a for or while loop. break仅在forwhile循环的上下文中才有意义。

But another problem is that your validationTest doesn't have a persistent view of the count variable - it's completely local, so the test isn't going to work anyway.但另一个问题是您的validationTest没有count变量的持久视图 - 它完全是本地的,所以无论如何测试都不会工作。 Consider passing a parameter instead, which will indicate whether the current call is recursive or not:考虑传递一个参数,该参数将指示当前调用是否是递归的:

validationTest(lastTry = false) {
    this.isAnyRangeInvalid = false;
    this.monthpicker.forEach(picker => {
        if (picker.isValidRange === false) {
            this.isAnyRangeInvalid = true;
        }
    });
    if (!lastTry) this.validationTest(true);
}

Make sure that the initial call of validationTest doesn't pass a parameter, or passes false .确保validationTest的初始调用不传递参数,或传递false

For a more general solution of limiting yourself to N recursive tries, you can pass around a number instead, eg:对于将自己限制为 N 次递归尝试的更通用的解决方案,您可以改为传递一个数字,例如:

validationTest(triesLeft = 3) {
    this.isAnyRangeInvalid = false;
    this.monthpicker.forEach(picker => {
        if (picker.isValidRange === false) {
            this.isAnyRangeInvalid = true;
        }
    });
    if (triesLeft !== 0) this.validationTest(triesLeft - 1);
}

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

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