在Angular 7中检查未定义的失败

时间:2019-04-24 13:09:38

标签: angular

我正在尝试对Angular 7中的数字变量进行未定义的检查。尽管该值未定义,但它不满足条件。你能告诉我我要去哪里了吗?

public init(val: string, selectedClassficationId: number) {
        this.Mode = val;
        if (selectedClassficationId !== undefined) {
        this.getClassificationDetails(selectedClassficationId);
        }
    }

2 个答案:

答案 0 :(得分:1)

为什么不尝试这个?

如果selectedClassficationId的值为undefinednullfalse0,则不会执行if块。

if (selectedClassficationId || selectedClassficationId == 0) {
  this.getClassificationDetails(selectedClassficationId);
}
else {
  console.log('The value is either undefined, null, false, 0', selectedClassficationId);
}

Here是每个用例的详细示例:

答案 1 :(得分:0)

您可以尝试

public init(val: string, selectedClassficationId: number) {
        this.Mode = val;
        if (selectedClassficationId != null) { // != null is check null as well as undefine at the same time 
        this.getClassificationDetails(selectedClassficationId);
        }
    }

我希望它可以帮助您