节点if语句执行顺序

时间:2015-06-20 23:45:42

标签: node.js

我很困惑为什么这个if语句会抛出JS错误。为什么函数一返回true就不会运行?

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null && res.locals.user.level > 5) {

2 个答案:

答案 0 :(得分:3)

&&声明中的if与此类似:

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null) {
   // at this point you know that res.locals.user is null
   if (res.locals.user.level > 5) {
       // won't get here because res.locals.user.level will throw an exception
   } 
}

如果&&比较的第一部分评估为真实,那么第二部分也将被评估,因为整个陈述为true,声明的两个部分必须是真实的。< / p>

看起来你可能想要这个:

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null || res.locals.user.level > 5) {
    // will get here because only the first term will be evaluated
    // since when the first term evaluates to true, the || is already satisfied
}

或者因为我不太确定你想要哪种逻辑,也许你想要这个:

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user !== null && res.locals.user.level > 5) {
    // will not get here because res.locals.user doesn't pass the first test
    // won't throw an exception because 2nd term won't be evaluated
}

答案 1 :(得分:1)

因为评估的第一部分是真的,所以它继续评估下一部分,然后在第一部分为真时总是抛出异常。这就像一个悖论:)

有些语言可以和&amp;&amp;如果第一个为真,则只执行第二个比较(如java)。但是,你所写的内容会以任何语言失败。您不能同时为空并且水平> 5。