【问题标题】:ternary operator causes an error inside if statement [closed]三元运算符在 if 语句中导致错误 [关闭]
【发布时间】:2017-08-17 07:33:26
【问题描述】:

为什么这个语句会导致 'TypeError: Cannot read property 'toString' of undefined' ?我想它会注意到und 是未定义的,只是避开它试图用und 生成字符串的那一行。 如果我从“if”语句中删除true ||,它可以正常工作

let und = undefined;

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

【问题讨论】:

  • true ||if 条件下的用途是什么?
  • 看来你对三元运算符的概念不太清楚
  • 实际代码不同,三元运算符在我的情况下是为了避免其他单独的语句
  • @Teemu 这就是我说有点的原因。我也知道这不是正确的术语。
  • `如果是真的?或未定义,如果“und”完全是“任何东西”,否则为假?????

标签: javascript if-statement ternary-operator


【解决方案1】:

这条指令:

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

将被读作:

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

由于OR 语句是trueund.toString() === 'anything' 将被执行,即使 und undefined

您需要在三元运算符周围加上括号。

let und = undefined;

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

【讨论】:

  • 一种复杂的打印方式"Yeah, no error thrown"
  • 每次评估的条件都是true,没有达到第二个表达式,是吗?
  • 这个表达式总是true
  • @Andreas 是的,确实是这样,只是在回答 OP 的问题。
  • @guest271314 我已经更新了答案,请查看详细说明
猜你喜欢
  • 2013-07-01
  • 1970-01-01
  • 2021-02-13
  • 2017-10-20
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
相关资源
最近更新 更多