首頁  >  問答  >  主體

使用ifelse語句來處理多個變數的組合情況

<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>
P粉420958692P粉420958692404 天前375

全部回覆(1)我來回復

  • P粉680087550

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

    您可以透過使用物件來讓您的邏輯更加資料驅動,例如:

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

    然後,您可以透過使用a存取該對象,並存取嵌套物件的值來設定您的outcome變量,例如:

    var outcome = outcomeMap[a][b];
    

    請注意,如果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語句更有效率。但是,如果您有更多可能性,它們應該更容易擴展。

    回覆
    0
  • 取消回覆