代码之家  ›  专栏  ›  技术社区  ›  Prozrachniy

三元运算符在if语句内导致错误[关闭]

  •  -2
  • Prozrachniy  · 技术社区  · 9 年前

    为什么此语句会导致“TypeError:无法读取未定义”的属性“toString”?我想它会注意到 und 未定义,只需避开它试图从中生成字符串的行 如果我删除 true || 根据“if”语句,它可以正常工作

    let und = undefined;
    
    if (true || und ? und.toString() === 'anything' : false) {
        // do something
    }
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   Erazihel    9 年前

    本说明:

    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');
    }