【问题标题】:Conditional operator not evaluating properly条件运算符未正确评估
【发布时间】:2019-05-04 19:13:02
【问题描述】:

问题

我正在尝试使用基于另一个变量的字符串值的条件运算符为变量赋值。

代码

const test = fnUserPlatform.platform === ('ps4' || 'xb1' || 'pc') ? 'p2.br.m0.weekly' : 'br.defaultsolo.current';

当 fnUserPlatform.platform 等于“ps4”时,测试正确评估为 p2.br.m0.weekly,但当 fnUserPlatform.platform 为“xb1”或“pc”时,它评估为“br.defaultsolo.current”,这是不正确的。

有谁知道为什么要这样评价?

【问题讨论】:

  • 你能发布你的函数吗?

标签: javascript conditional-operator


【解决方案1】:

通过使用这个表达式,

'ps4' || 'xb1' || 'pc'

你得到第一个字符串,因为这个字符串是一个truthy 值,并且通过使用logical OR ||,这个值是这个表达式的结果。

如果第一个值是空字符串,则取第一个真值

'' || 'xb1' || 'pc'
      ^^^^^

为了更好地检查您是否有一个项目和一些值,您可以获取一个数组并使用Array#includes 进行检查。

const
    test = ['ps4', 'xb1', 'pc'].includes(fnUserPlatform.platform)
       ? 'p2.br.m0.weekly'
       : 'br.defaultsolo.current';

【讨论】:

    【解决方案2】:

    尝试这样做:

    const test = fnUserPlatform.platform === 'ps4' ? 'p2.br.m0.weekly' : fnUserPlatform.platform === 'xb1' ? 'p2.br.m0.weekly' : fnUserPlatform.platform === 'pc' ? 'p2.br.m0.weekly' : 'br.defaultsolo.current';
    

    【讨论】:

    • 没有括号,它总是对 false 选项的评估不正确。当我添加括号时,它修复了 fnUserPlatform.platform 为“ps4”但没有修复 xb1 或 pc 时的问题
    猜你喜欢
    • 2011-08-04
    • 2019-09-23
    • 1970-01-01
    • 2013-03-09
    • 2012-05-18
    • 1970-01-01
    • 2019-04-01
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多