在if语句中获取失败条件

get failing condition in if statement

本文关键字:失败 条件 获取 if 语句      更新时间:2023-09-26

考虑下面的if语句

if (a === null || b === null || c === null) {
    // I want the failing condition
}

是否有可能得到失败的条件而不需要检查每一个

if (a === null || b === null || c === null) {
    if (a===null){alert('a failed the check');}
    if (b===null){alert('b failed the check');}
    if (c===null){alert('c failed the check');}
}

我知道在上面的例子中,很容易使它动态,考虑一个真实世界的例子,其中执行不同的测试。

不可能,在if块中不可能得到求值为true的条件。

当然,因为您使用了or条件,您的代码可以简单地为

if (a===null){alert('a failed the check');}
else if (b===null){alert('b failed the check');}
else if (c===null){alert('c failed the check');}

不带外部if

如果你想知道哪个条件是失败的,那么你需要明确地声明,在你的if条件,否则有没有方式。像这样:

if(a===null){alert('a failed the check');}
    else if (b===null){alert('b failed the check');}
    else {alert('c failed the check');}

边注:

当您使用||运算符时,一旦满足第一个false条件,它就不会检查下一个条件。

你可以做类似的事情:

var failed = false;
if (a===null){alert('a failed the check');failed=true;}
if (b===null){alert('b failed the check');failed=true;}
if (c===null){alert('c failed the check');failed=true;}
if (failed) { /* common logic */ }