Javascript 用循环替换多个if语句?
是否可以通过在数组中循环并替换Javascript 用循环替换多个if语句?,javascript,jquery,Javascript,Jquery,是否可以通过在数组中循环并替换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);
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);
}
可以使用数组的索引替换数字
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);
}
}
让com_数组=['ON','OFF','ON'];
对于(索引=0;索引
假设要对数组中的所有元素执行此操作,可以使用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语句,并在bootstrapSwitch中使用“element=='ON'作为条件:
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"))
我使它与IE-11兼容(即没有箭头函数和字符串模板文字)。因为我假设您没有透明步骤
对于不兼容IE的答案(现代js),请用代码检查问题的第一条注释。您可以创建一个函数并重用它:
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")
是………
com_数组。forEach((state,index)=>{$(`input[name=“shelf-${index+1}]”)。bootstrapSwitch('state',state===“ON”);})
仍然重复。for in
是循环数组的一种不好的做法
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")