[英]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?可以通过循环遍历数组并替换
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);
}
Assuming that you want to do this for all elements inside the array, you can use a forEach loop as so:假设您想对数组中的所有元素执行此操作,您可以使用 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);
}
})
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:如果你想让它更干净、更少重复,你可以取消 if-else 语句,并使用 "element == 'ON' 作为 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).我使它与 IE-11 兼容(即没有箭头函数和字符串模板文字)。 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.对于非 IE 兼容的答案(现代 js),请使用代码检查问题的第一条评论。
You could create a function and reuse it:您可以创建一个 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")
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.