2013-03-12 41 views
4

lsEstimator是具有2個元素的陣列,該函數返回true這兩個JS函數爲什麼不同?

function got_estimators() { 
    var retval = 
    (typeof lsEstimator != 'undefined' && 
    lsEstimator != null && 
    lsEstimator.length > 0); 
    return retval; 
} 

但此函數不(它返回undefined,我想,在瀏覽器和FF):

function got_estimators() { 
    return 
     (typeof lsEstimator != 'undefined' && 
     lsEstimator != null && 
     lsEstimator.length > 0); 
} 

爲什麼?

+0

@FelixKling,因爲它是正確的一個,你應該寫一個答案。 – mpm 2013-03-12 12:49:30

+0

哇。 1分鐘很不錯。那麼第二個函數實際上做了什麼? – EML 2013-03-12 12:50:01

+1

自動分號插入是所有邪惡的根源:-( – Bergi 2013-03-12 12:51:58

回答

17

由於第二個示例中return之後的換行符。代碼評估爲:

function got_estimators() { 
    return; // <-- bare return statement always results in `undefined`. 
    (typeof lsEstimator != 'undefined' && 
    lsEstimator != null && 
    lsEstimator.length > 0); 
} 

JavaScript甚至沒有評估邏輯運算符。

爲什麼會發生這種情況?因爲JavaScript有自動分號插入,即它試圖在分號「插入分號」(more information here)處插入分號。

return關鍵字和返回值在同一行:

return (typeof lsEstimator != 'undefined' && 
    lsEstimator != null && 
    lsEstimator.length > 0); 
+0

在句子行上放置大括號的唯一原因! – jAndy 2013-03-12 12:51:36

+0

這真是太神奇了,剛剛在http://oreilly.com/找到了Crockford的JavaScript'可怕部分'。 javascript/excerpts/javascript-good-parts/awful-parts.html,並且在第3號出現。 – EML 2013-03-12 13:15:40

相關問題