【问题标题】: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.colorVariant 与 success 不同,然后它转到 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'