【问题标题】:Nested ternary operator not returning as expected嵌套三元运算符未按预期返回
【发布时间】:2020-11-24 17:54:57
【问题描述】:

我正试图围绕嵌套的三元操作。

colorVariant 的值是 'success'、'info'、'error' 或 'default'。

props.colorVariant == 'success' ? 'green' : 'info' ? 'gray' : 'error' ? 'red' : 'default' ? 'black' : 'purple'

目前,我已将该值设置为“默认”,因为我希望看到它一直到最后,但就目前而言,返回的颜色是灰色。

有人能解释一下为什么会这样吗?

【问题讨论】:

  • 您应该使用带有键/值的地图(对象)

标签: javascript conditional-operator


【解决方案1】:

您必须在每个条件下进行比较,例如:

props.colorVariant == 'success'
  ? 'green'
  : props.colorVariant === 'info'
    ? 'gray'
    : props.colorVariant === 'error'
       ? // ...

但在这里使用对象会更有意义:

const colorsByVariant = {
  success: 'green',
  info: 'gray',
  error: 'red',
  default: 'black',
};
const color = colorsByVariant[props.colorVariant] ?? 'purple';

【讨论】:

    【解决方案2】:

    您需要检查变量。如果不是第一个非空字符串是真的。

    props.colorVariant === 'success'
        ? 'green'
        : props.colorVariant === 'info'
            ? 'gray'
            : props.colorVariant === 'error'
                ? 'red'
                : props.colorVariant === 'default'
                    ? 'black'
                    : 'purple'
    

    【讨论】:

      【解决方案3】:

      您必须在: 之后重复条件 而不是

          props.colorVariant == 'success' ? 'green' : 'info' ? 'gray' : 'error' ? 'red' : 'default' ? 'black' : 'purple'
      

      你应该做以下事情

      props.colorVariant == 'success' ? 'green' : props.colorVariant == 'info' ? 'gray' : props.colorVariant == 'error' ? 'red' : props.colorVariant == 'default' ? 'black' : 'purple'
      

      此刻你得到“灰色”是因为:

      props.colorVariantsuccess 不同,然后它转到 info 但没有条件所以它是真的(因为字符串被强制转换为 booleaqn 总是正确的)然后你得到gray

      【讨论】:

        【解决方案4】:

        props = {colorVariant: ''} // just here for the demo
        
        const color = props.colorVariant == 'success' ? 'green' :
        props.colorVariant == 'info' ? 'gray' :
        props.colorVariant == 'error' ? 'red' :
        props.colorVariant == 'default' ? 'black' : 'purple';
        
        console.log('color:', color); // purple
        props.colorVariant == 'success' ? 'green' : props.colorVariant == 'info' ? 'gray' : props.colorVariant == 'error' ? 'red' : props.colorVariant == 'default' ? 'black' : 'purple'
        

        【讨论】:

          猜你喜欢
          • 2019-12-10
          • 2018-02-19
          • 2012-12-22
          • 2020-01-09
          • 1970-01-01
          • 2011-10-29
          相关资源
          最近更新 更多