2017-08-17 96 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

这个表达总是'真的' –