Typescript 布尔函数必须返回一个值

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

Typescript boolean function must return a value

typescript

提问by redux17

I have following Typescript boolean function:

我有以下 Typescript 布尔函数:

checkRiskValues(): boolean {
    this.controlsName.forEach((item) => {
        this.threatForm.get(item)!.valueChanges.subscribe(value => {
            this.valueControlArray.push(this.threatForm.get(item)!.value);

            if (this.valueControlArray.indexOf(true) > -1)
                return true;

            else
                return false
        });
    });
}

The method appears error the function must return value. I know it, but I'm not sure how to implement this true/false statement outside foreach scope ?

该方法出现错误函数必须返回值。我知道,但我不确定如何在 foreach 范围之外实现这个 true/false 语句?

If I call if/else statament outside foreach loop result is always false because

如果我在 foreach 循环之外调用 if/else statament 结果总是假的,因为

if (this.valueControlArray.indexOf(true) > -1)

is empty..

是空的..

EDIT

编辑

I've deleted checkRiskValues() function and add complete logic in ngOnInit() method and I'have also added valueControl varibable that keep true/false value and pass in another function. Thanks everyone..This my solution:

我已经删除了 checkRiskValues() 函数并在 ngOnInit() 方法中添加了完整的逻辑,并且我还添加了 valueControl 变量以保持真/假值并传入另一个函数。谢谢大家..这是我的解决方案:

ngOnInit() {
    this.controlsName.forEach((item) => {
        this.threatForm.get(item)!.valueChanges.subscribe(value => {
            this.valueControlArray.push(this.threatForm.get(item)!.value);

            if (this.valueControlArray.indexOf(true) > -1) {
                this.valueControl = true;

            }
            else {
                this.valueControl = false;
            }
        });
    });
}

回答by axl-code

This is my proposal:

这是我的提议:

checkRiskValues(): boolean {
    return setRiskValues().indexOf(true) > -1;
}

setRiskValues(): Array<any> {
    let values = [];
    this.controlsName.forEach((item) => {
        this.threatForm.get(item)!.valueChanges.subscribe(value => {
            values.push(this.threatForm.get(item)!.value);
        });
    });

    return values;
}

This way you are:

这样你是:

  1. Building your array
  2. Checking if exists a positive value (if true is present will return the index)
  1. 构建你的阵列
  2. 检查是否存在正值(如果存在则返回索引)