2015-06-20 61 views
0

我很困惑,爲什麼這個if語句會拋出JS錯誤。爲什麼函數一返回true就不會運行?節點if語句執行順序

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

這是一個和所以它必須評估兩個參數?你的意思是'!=='null? – Jason

+0

嗯,我不會想到它將需要評估兩者,因爲它已經恢復正確。我猜這就是我要出錯的地方。這是我對JS的理解。此外,沒有爲測試的目的'=== null' :)阿格球是的,你是對的... JS 101失敗了! '&&'都需要是真的......我責備時間? –

回答

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

如果&&比較的第一部分計算爲truthy,那麼第二部分也將因爲評估整個語句是true ,這兩項聲明都必須真實。


看來,你可能想這個代替:

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

因爲評估的第一部分是真的,所以它繼續評估下一個部分,然後總是會拋出一個異常,因爲第一部分是真的。這就像一個悖論:)

有語言,其中& &只執行第二次比較如果第一個是真的(如java)。但是,您所寫的內容會以任何語言失敗。您不能一次爲null並且級別> 5。

+1

我在這裏死去...大聲笑感謝提醒,10年做php/js ...:p你以爲你會知道簡單的事情:p –