0

我正在使用一个小脚本,它使用以下代码将自定义选择添加到保管箱

if (typeof customsum1 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum1); }
if (typeof customsum2 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum2); }
if (typeof customsum3 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum3); }

等等。这可以通过添加更多行来扩展,但是由于变量具有相同的格式,有没有办法将其压缩为理论上允许无限的自定义选择,只要设置的变量遵循 customsum# 格式?

4

2 回答 2

4

使用数组和循环:

var sums = [customsum1, customsum2, customsum3];

for (var i=0; i<sums.length; i++) {
    if (typeof sums[i] !== 'undefined') {
         editsummAddOptionToDropdown(dropdown, sums[i]);
    }
}
于 2013-01-17T00:11:16.917 回答
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]);
}
于 2013-01-17T00:13:26.837 回答