简体   繁体   中英

Nested ternary operator not returning as expected

I'm trying to wrap my head around nested ternary ops.

The value of colorVariant is either 'success', 'info', 'error', or 'default'.

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

At the moment, I've set the value to 'default' as I'd like to see it make it all the way to the end, but as it stands, the colour being returned is gray.

Could someone explain why this is the case?

You'll have to carry out the comparison in each condition, eg:

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

But it'd make much more sense to use an object here:

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

 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'

You need to check against the variable. If not the first not empty string is truthy.

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

You have to repeat the condition after the : instead of

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

you should do the following

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

At the moment You get 'gray' because:

props.colorVariant is different to success then it goes to info but there is no condition so it's true (because a string is casted to a booleaqn is always true) then you got gray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM