我正在使用一个小脚本,使用以下代码将自定义选项添加到保管箱
if (typeof customsum1 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum1); }
if (typeof customsum2 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum2); }
if (typeof customsum3 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum3); }
等等。这可以通过添加更多行来扩展,但由于变量具有相同的格式,有没有办法将其压缩到理论上允许无限自定义选择,只要设置变量遵循Customsum#format?
答案 0 :(得分:4)
使用数组和循环:
var sums = [customsum1, customsum2, customsum3];
for (var i=0; i<sums.length; i++) {
if (typeof sums[i] !== 'undefined') {
editsummAddOptionToDropdown(dropdown, sums[i]);
}
}
答案 1 :(得分:4)
假设这些是全局变量,您可以使用循环:
for( var i=1; i<=3; i++) {
if( typeof window['customsum'+i] != "undefined") editsummAddOptionToDropdown(dropdown,window['customsum'+i]);
}
但是,最好还是使用数组:
var customsum = [
/* what you normally have for customsum1 */,
/* same for customsum2 */,
...
];
for( var i=0, l=customsum.length; i<l; i++) {
if( typeof customsum[i] != "undefined") editsummAddOptionToDropdown(dropdown,customsum[i]);
}