JS Ternary functions with multiple conditions?

前端 未结 9 546
花落未央
花落未央 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 05:15
    var r = inputOne == "" ? "" : ( 
    inputOne == "Yes" ? "517" : "518");
    
    0 讨论(0)
  • 2020-12-31 05:16

    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.

    0 讨论(0)
  • 2020-12-31 05:22

    Yes, you can use multiple condition in Ternary Operator. Hope this will help you.

    var x=20;
    var y = x<13 ? "Child" : x<20 ? "Teenage" : x<30 ? "Twenties" : "Old people";
    console.log(y);
    
    0 讨论(0)
提交回复
热议问题