User ternary operator for 3 possible outcomes

2019-06-14 19:51发布

问题:

I want to write a ternary operator based on the following;

var statusJSON = {
    '- Select -': '',
    'Active': true,
    'Inactive': false
};

Currently I have

statusFlag: $('#statusFlag').val() == 'true' ? true : false

This works fine for true and false values, but does not handle the 3rd condition (i.e. empty "")

How do I handle the same ?

回答1:

statusFlag: $('#statusFlag').val() == 'true' ? true : 
            $('#statusFlag').val() == '' ? 'empty' : false

You can just add multiple conditions like this:

a ? b : (c ? d : e)

() aren't necessary, but in my opinion, they improve readability when you write it without linebreaks.

This means:

if(a){
    b
}else{
    if(c){
        d
    }else{
        e
    }
}

So, basically, you're nesting another ternary operator in the else clause of the previous one. You can go as far as you'd like with this:

a ? b :   // if(a) then `b`
c ? d :   // else, if(c) then `d`
e ? f :   // else, if(e) then `f`
g ? h :   // else, if(g) then `h`
i ? j : k // else, if(i) then `j`, else `k`


回答2:

Try to nest the ternary operator,

statusFlag: $('#statusFlag').val() == 'true' ?
          true : $('#statusFlag').val() == 'false' ? false : "empty";


回答3:

You want to use 2 conditionals in the ternary expression, something like:

value = (condition1) ? a : (condition2) ? c : d;

Your case:

statusFlag: $('#statusFlag').val() == 'true' ? true : 
        $('#statusFlag').val() == '' ? 'empty' : false


回答4:

You can use statusJSON as a lookup table:

var val = $('#statusFlag').val();
… statusFlag: val in statusJSON ? statusJSON[val] : false /*or whatever*/

If you're sure that only the three values do occur, or are fine with an undefined outcome otherwise, you might as well just use

… statusFlag: statusJSON[$('#statusFlag').val()]