爲什麼這個語句導致'TypeError:Can not read property'toString'of undefined'?我認爲它會注意到und
是未定義的,只是避免嘗試使字符串從und
中刪除。 如果我從 'if' 語句,它工作正常三元運算符在語句內部導致錯誤
let und = undefined;
if (true || und ? und.toString() === 'anything' : false) {
// do something
}
爲什麼這個語句導致'TypeError:Can not read property'toString'of undefined'?我認爲它會注意到und
是未定義的,只是避免嘗試使字符串從und
中刪除。 如果我從 'if' 語句,它工作正常三元運算符在語句內部導致錯誤
let und = undefined;
if (true || und ? und.toString() === 'anything' : false) {
// do something
}
該指令刪除true ||
:
true || und ? und.toString() === 'anything' : false
將被讀爲:
(true || und) ? und.toString() === 'anything' : false
由於OR
聲明true
,und.toString() === 'anything'
將被執行,即使und
是undefined
。
您需要在三元運算符周圍放置括號。
let und = undefined;
if (true || (und ? und.toString() === 'anything' : false)) {
console.log('Yeah, no error thrown');
}
什麼是''if'條件中'真||的目的是什麼? – guest271314
看來你的三元運算符的概念還不清楚 –
它在實際代碼中有所不同,三元運算符是爲了避免在我的例子中使用其他單獨的語句 – Prozrachniy