簡體   English   中英

用循環替換多個if語句?

[英]Replace multiple if statements with loop?

可以通過循環遍歷數組並替換input[name="shelf-1"]中的數字而不是使用多個 if 語句來縮短此代碼嗎?

if(com_array[0] == "ON")
{
    $('input[name="shelf-1"]').bootstrapSwitch('state', true);
}else{
    $('input[name="shelf-1"]').bootstrapSwitch('state', false);
}

if(com_array[1] == "ON")
{
    $('input[name="shelf-2"]').bootstrapSwitch('state', true);
}else{
    $('input[name="shelf-2"]').bootstrapSwitch('state', false);
}

if(com_array[3] == "ON")
{
    $('input[name="shelf-3"]').bootstrapSwitch('state', true);
}else{
    $('input[name="shelf-3"]').bootstrapSwitch('state', false);
}

假設您想對數組中的所有元素執行此操作,您可以使用 forEach 循環,如下所示:

com_array.forEach( (element, index) => {
    if(element == "ON") {
        $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', true);
    }else{
        $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', false);
    }
})

更新重構選項:

如果你想讓它更干凈、更少重復,你可以取消 if-else 語句,並使用 "element == 'ON' 作為 bootstrapSwitch 中的條件:

 com_array.forEach( (element, index) => {
        $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', element == "ON");
})

然后你可以進一步重構為一行

com_array.forEach((element, index) => $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', element == "ON"))
com_array.forEach(function(com, index) {
        $('input[name="shelf-' + (index + 1) + '"]').bootstrapSwitch(
            'state',
            com == 'ON'
        )
    }
);

我使它與 IE-11 兼容(即沒有箭頭函數和字符串模板文字)。 因為我假設您沒有轉譯步驟。

對於非 IE 兼容的答案(現代 js),請使用代碼檢查問題的第一條評論。

您可以創建一個 function 並重用它:

const bootstrapSwitch = (key, value) = {
  $(`input[name="shelf-${key}"]`).bootstrapSwitch('state', value);
}

bootstrapSwitch(0, com_array[1] == "ON")
bootstrapSwitch(1, com_array[2] == "ON")
bootstrapSwitch(3, com_array[3] == "ON")

您可以使用數組的索引替換數字。

let com_array = ['ON','OFF','ON'];
for (index = 0; index < com_array.length; index++) {
  if (com_array[index] === 'ON') {
    $('input[name="shelf-'+(index+1)+'"]').bootstrapSwitch('state', true);
  } else {
    $('input[name="shelf-'+(index+1)+'"]').bootstrapSwitch('state', false);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM