三元运算符在 if 语句中导致错误
ternary operator causes an error inside if statement
为什么此语句会导致“类型错误:无法读取未定义的 属性 'toString'”?我认为它会注意到 und
是未定义的,只是避开它试图从 und
中创建字符串的那一行。
如果我从 'if' 语句中删除 true ||
它工作正常
let und = undefined;
if (true || und ? und.toString() === 'anything' : false) {
// do something
}
这条指令:
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');
}
为什么此语句会导致“类型错误:无法读取未定义的 属性 'toString'”?我认为它会注意到 und
是未定义的,只是避开它试图从 und
中创建字符串的那一行。
如果我从 'if' 语句中删除 true ||
它工作正常
let und = undefined;
if (true || und ? und.toString() === 'anything' : false) {
// do something
}
这条指令:
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');
}