search

Home  >  Q&A  >  body text

Use the ifelse statement to handle combinations of multiple variables

<p>I have two variables as follows: </p> <pre class="brush:php;toolbar:false;">var a = "active" //[Two possible values ​​active/inactive] var b = "inactive" //[Three possible values ​​active/locked/disabled] var outcome = "" if(a=="active" && b=="active") outcome = "a"; elif(a=="active" && b=="locked") outcome = "b" elif(a=="active" && b=="disabled") outcome = "c" elif(a=="inactive" && b=="active") outcome = "d" elif(a=="inactive" && b=="disabled") outcome = "e" elif(a=="inactive" && b=="locked") outcome = "f"</pre> <p>In JS, besides using ifelse to check different conditions, what is the most efficient way to describe possible outcomes? Please provide suggestions. </p>
P粉420958692P粉420958692474 days ago415

reply all(1)I'll reply

  • P粉680087550

    P粉6800875502023-08-19 00:33:06

    You can make your logic more data-driven by using objects, for example:

    var outcomeMap = {
      active: {
        active: "a",
        locked: "b",
        disabled: "c"
      },
      inactive: {
        active: "d",
        locked: "e",
        disabled: "f",
      }
    };
    

    You can then set your outcome variable by accessing that object using a and accessing the value of the nested object, for example:

    var outcome = outcomeMap[a][b];
    

    Please note that if a can be any other value than the one you mentioned, it is better to check outcomeMap[a] before accessing b Whether it is undefined. This can be done using optional chaining if your environment supports it, for example: outcomeMap[a]?.[b];

    Alternatively, you can set up an array containing the possible combinations and then loop through them to check if your combination matches. Then, based on the current index, if a result is found, you can index to your result (outcomes), for example:

    function getOutcome(a, b) {
      const aVals = ['active', 'inactive'];
      const bVals = ['active', 'locked', 'disabled'];
      const outcomes = [['a', 'b', 'c'], ['d', 'e', 'f']];
    
      for(const [i, aVal] of aVals.entries()) {
        for(const [j, bVal] of bVals.entries()) {
          if (aVal == a && bVal == b) {
            return outcomes[i][j];
          }
        }
      }
      // return ''; if you want a default value of empty string
    }
    const outcome = getOutcome('inactive','locked');
    console.log(outcome);

    Please note that neither method is more efficient than using an if statement. However, if you have more possibilities, they should be easier to scale.

    reply
    0
  • Cancelreply