繁体   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