Use the ifelse statement to handle combinations of multiple variables
P粉420958692
2023-08-18 14:08:36
<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>
You can make your logic more data-driven by using objects, for example:
You can then set your
outcome
variable by accessing that object usinga
and accessing the value of the nested object, for example:Please note that if
a
can be any other value than the one you mentioned, it is better to checkoutcomeMap[a]
before accessingb
Whether it isundefined
. 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: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.