<p>我有两个变量如下:</p>
<pre class="brush:php;toolbar:false;">var a = "active" //[两个可能的值 active/inactive]
var b = "inactive" //[三个可能的值 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>在JS中,除了使用ifelse检查不同条件之外,描述可能的结果最有效的方式是什么?请提供建议。</p>
您可以通过使用对象使您的逻辑更加数据驱动,例如:
var outcomeMap = { active: { active: "a", locked: "b", disabled: "c" }, inactive: { active: "d", locked: "e", disabled: "f", } };然后,您可以通过使用
a访问该对象,并访问嵌套对象的值来设置您的outcome变量,例如:请注意,如果
a除了您提到的值之外还可以是任何其他值,最好在访问b之前检查outcomeMap[a]是否为undefined。如果您的环境支持,可以使用可选链来完成,例如:outcomeMap[a]?.[b];或者,您可以设置包含可能组合的数组,然后循环遍历它们以检查您的组合是否匹配。然后,根据当前索引,如果找到结果,您可以索引到您的结果(
outcomes),例如: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);请注意,这两种方法都不比使用if语句更高效。但是,如果您有更多可能性,它们应该更容易扩展。