Javascript 获取if语句中的失败条件

Javascript 获取if语句中的失败条件,javascript,Javascript,考虑下面的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

考虑下面的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
块中不可能获得评估为真的条件

当然,因为您使用了
条件,所以您的代码可能只是

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
No,则在
if
块中不可能获得评估为true的条件

当然,因为您使用了
条件,所以您的代码可能只是

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
条件中明确说明,否则存在no方式。大概是这样的:

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


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

如果您想知道哪个条件失败,那么您需要在
如果
条件中明确说明,否则有方法。大概是这样的:

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 */ }

你可以做类似的事情:

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 */ }

为什么不先做每个检查并将其存储在一个变量中。你可以使用一个函数来检查变量是否为null,这将最小化你的代码字节。虽然它需要相同的时间检查这个答案,但它满足了完全相同的需要:哇,很好,find@techfoobar-我甚至在回答之前寻找过一个#searchfail@Jamiec-我之所以能指出这一点,是因为我在几个小时前回答了另一个问题,而这一问题在我的记忆中仍然历历在目:-)为什么不先做每个检查并将其存储在一个变量中。你可以使用一个函数来检查变量是否为null,这将最小化你的代码字节。虽然它需要相同的时间检查这个答案,但它满足了完全相同的需要:哇,很好,find@techfoobar-我甚至在回答之前寻找过一个#searchfail@Jamiec-我之所以能指出这一点,是因为我在几个小时前回答了另一个问题,而这一问题在我的记忆中仍然历历在目:-)