JS Ternary functions with multiple conditions?

前端 未结 9 598
花落未央
花落未央 2020-12-31 04:44

I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:

         


        
9条回答
  •  半阙折子戏
    2020-12-31 04:55

    Unfortunately JavaScript does not provide a super terse and readable way to do this. Personally I would just use some single-line if statements like this:

    var inputOneAns;
    if (inputOne === 'Yes') inputOneAns = '517';
    if (inputOne === 'No') inputOneAns = '518';
    else inputOneAns = '';
    

    Which can be even cleaner if you abstract it into a function (note: no need for else in this case):

    function getInputOneAns(inputOne) {
        if (inputOne === 'Yes') return '517';
        if (inputOne === 'No') return '518';
        return '';
    }
    

    Personally, I don't really like switch statements for this for two reasons: firstly those extra break statements bloating the code, and secondly, switch statements are very limiting - you can only do simple equality checks, and only against a single variable. Besides, in the case that you know you will be always checking a single string I would favour a simple map object:

    var map = { 'Yes': '517', 'No': '518' };
    var inputOneAns = map[inputOne] || '';
    

提交回复
热议问题