简体   繁体   中英

Replace multiple if statements with loop?

Can this code be shortened by looping through the array and replacing the number in input[name="shelf-1"] instead of having multiple if statements?

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);
}

Assuming that you want to do this for all elements inside the array, you can use a forEach loop as so:

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);
    }
})

Updated for refactoring option:

If you want it to be cleaner and less repetitive, you can do away with the if-else statement, and use "element == 'ON' as the condition inside bootstrapSwitch:

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

And then you can refactor further to one line

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'
        )
    }
);

I made it IE-11 compatible (ie no arrow functions and string template literals). Because I assume you have no transpilation step.

For the non-IE compatible answer (modern js) check the first comment to the question with code.

You could create a function and reuse it:

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")

You can replace the numbers using the index of the array.

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM