當表達式中的一個條件結果爲false時,我能否指望Javascript立即失敗嗎?Javascript有條件排序評估
f = {'a':'b'};
if (f.a !== undefined || f.a === 'b') {
// Is this OK to use, because the second condition will never be evaluated?
}
當表達式中的一個條件結果爲false時,我能否指望Javascript立即失敗嗎?Javascript有條件排序評估
f = {'a':'b'};
if (f.a !== undefined || f.a === 'b') {
// Is this OK to use, because the second condition will never be evaluated?
}
是的,這就是所謂的short circuit evaluation。
如果邏輯運算符爲AND
,如果第一個計算結果爲false
,那麼第二個計算結果從不計算,因爲該條件已知足夠滿足要求。
與OR
邏輯運算符,如果第一個是false
,它將評估第二個。否則,如果第一個是true
它不會評估第二個(不需要)。
這也是爲什麼你看到...
var a = function(b) {
b = b || 7;
}
'b = b || 7;'form通常用來作爲一種簡短的方式來爲b未定義時提供一個默認值,因爲undefined的計算結果爲false,但*實際上並不工作*因爲b可以保存其他幾個值也計算爲false(0,null,一個空字符串,當然false都計算爲false)。當然,如果你確信所有這些其他值都應該被默認值覆蓋,那麼OK ... – nnnnnn 2011-05-05 02:35:37
@nnnnn這並不完美,但很多時候,這非常有用。 – alex 2011-05-05 02:37:19
我認爲正確的方法是'b = typeof b =='undefined'?7:b;' – JVE999 2014-09-30 19:52:05
從我在代碼中看到你的第二個條件始終評估,因爲(f.a!==未定義)等於true。 – a1ex07 2011-05-05 01:40:48
@ a1ex07謝謝,修正。 – ash 2011-05-05 01:42:07
如果第一個條件評估爲false,則會評估第二個條件。 – RobG 2011-05-05 01:43:33