我有一个基本上包含3个值的数组:
如果数组中存在元素,则此值用于禁用html中的元素。我创建的一段代码正在工作但看着它,必须有更好的方法来编写它。
for (var i = 0; i < firmwareTypes.length; i++) {
if (firmwareTypes[i] == "listingname") {
parameterlistingname.required = false;
parameterlistingfile.required = false;
}
if (firmwareTypes[i] == "listingdummy") {
parameterlistingdummyname.required = false;
parameterlistingdummyfile.required = false;
}
if (firmwareTypes[i] == "bootloadername") {
bootloadername.required = false;
bootloaderfile.required = false;
}
}
有没有一种方法在javascript中比较某些字符串长度的id元素,所以我可以只使用一个if条件。类似的东西:
for (var i = 0; i < firmwareTypes.length; i++) {
if (firmwareTypes[i].contains(???) {
bootloader*.required = false;
}
}
或者只是让代码更清洁?
答案 0 :(得分:1)
如果您使用的是对象而不是多个变量,那么您可以更简单地使用它:
var fileParameters = {
listingname: {required: true},
listingdummy: {required: true},
bootloadername: {required: true}
};
var nameParameters = {
listingname: {required: true},
listingdummy: {required: true},
bootloadername: {required: true}
};
for (var i = 0; i < firmwareTypes.length; i++) {
if (firmwareTypes[i] in fileParameters) {
fileParameters[firmwareTypes[i]].required = false;
nameParameters[firmwareTypes[i]].required = false;
}
}
答案 1 :(得分:1)
您可以使用一些方法来优化if
语句。
使用switch
:
switch (firmwareTypes[i]) {
case 'listingname':
parameterlistingname.required = false;
parameterlistingfile.required = false;
break;
case 'listingdummy':
parameterlistingdummyname.required = false;
parameterlistingdummyfile.required = false;
break;
case 'bootloadername':
bootloadername.required = false;
bootloaderfile.required = false;
break;
}
请注意每个案例末尾的break;
语句。
您可以在此MDN article中详细了解switch
。
分别指定每个变量:
var ft = firmwareTypes[i];
parameterlistingname.required = (ft === 'listingname');
parameterlistingfile.required = (ft === 'listingname');
parameterlistingdummyname.required = (ft === 'listingdummy');
parameterlistingdummyfile.required = (ft === 'listingdummy');
bootloadername.required = (ft === 'bootloadername');
bootloaderfile.required = (ft === 'bootloadername');
答案 2 :(得分:1)
也许这可能会奏效:
var types = {
'listingname': [parameterlistingname, parameterlistingfile],
'listingdummy': [parameterlistingdummyname, parameterlistingdummyfile],
'bootloadername': [bootloadername, bootloaderfile]
};
firmwareTypes.forEach(function (firmware) {
if (firmware in types) {
types[firmware].forEach(function (item) {
item.required = false;
});
}
});