为什么这个语句导致'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