2017-08-17 40 views
-2

爲什麼這個語句導致'TypeError:Can not read property'toString'of undefined'?我認爲它會注意到und是未定義的,只是避免嘗試使字符串從und中刪除。 如果我從 'if' 語句,它工作正常三元運算符在語句內部導致錯誤

let und = undefined; 

if (true || und ? und.toString() === 'anything' : false) { 
    // do something 
} 
+0

什麼是''if'條件中'真||的目的是什麼? – guest271314

+0

看來你的三元運算符的概念還不清楚 –

+0

它在實際代碼中有所不同,三元運算符是爲了避免在我的例子中使用其他單獨的語句 – Prozrachniy

回答

0

該指令刪除true ||

true || und ? und.toString() === 'anything' : false 

將被讀爲:

(true || und) ? und.toString() === 'anything' : false 

由於OR聲明trueund.toString() === 'anything'將被執行,即使undundefined

您需要在三元運算符周圍放置括號。

let und = undefined; 
 

 
if (true || (und ? und.toString() === 'anything' : false)) { 
 
    console.log('Yeah, no error thrown'); 
 
}

+1

打印''是,沒有錯誤拋出'的複雜方式' – Andreas

+1

條件會在每次評估中都是「真實的」,而不是第二個表達,是的? – guest271314

+0

這個表達總是'真的' –