JS Ternary functions with multiple conditions?

戏子无情 提交于 2019-12-03 07:03:24

Yes you can go wild nesting ternaries. I find this version to be fairly readable:

var foo = (
  bar === 'a' ? 1 : // if 
  bar === 'b' ? 2 : // else if 
  bar === 'c' ? 3 : // else if
  null // else 
);

but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.

A switch statement is likely the best choice in a situation like this.

let inputOneAns;
switch(inputOne) {
  case "Yes":
   inputOneAns = "517";
   break;
  case "No":
   inputOneNas = "518";
   break;
  default:
   inputOneNas = "";
}

If you could do ternary operations beyond 2 conditions, they would become incredibly messy. You can put conditions together, but I've no idea why you would want that - that would be incredibly messy.

var r = inputOne == "" ? "" : ( 
inputOne == "Yes" ? "517" : "518");

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] || '';

Yeh you can chain them together much like using an else if statement, but it can sometimes be a bit hard to read though, so I tend to split mine over multiple lines.

var inputOneAns = inputOne == 'Yes' ? '517' :
  inputOne == 'No' ? '518' : '';

However in this case I would suggest a switch statement seeing as you're comparing the same value for every case.

Seems like a classic use for a switch statement:

let inputOneAns = '';
switch(inputOne) {
  case 'Yes':
    inputOneAns = "517";
    break;
  case 'No': 
    inputOneAns = "518";
    break;
  default:
    inputOneAns = "";
}
  • note you don't actually need the default case, but I find it makes things more readable.

The most elegant and clean way is to take advantage of Object literals:

const Switch = (str) => ({
  "Yes": "517",
  "No": "518",
})[str] || '';

console.log(Switch("Yes")); // 517
console.log(Switch("No"));  // 518
console.log(Switch("Non matching value")); // Empty

This has the advantage of being both readable and flexible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!