Reputation: 5
I am using a small script that adds custom selections to a dropbox using the following code
if (typeof customsum1 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum1); }
if (typeof customsum2 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum2); }
if (typeof customsum3 != "undefined") { editsummAddOptionToDropdown(dropdown, customsum3); }
and so on. This is expandable by adding more lines, but since the variables have the same format, is there a way to condense this to theoretically allow infinite custom selections as long as the set variables follow the customsum# format?
Upvotes: 0
Views: 75
Reputation: 359786
Use an array and a loop:
var sums = [customsum1, customsum2, customsum3];
for (var i=0; i<sums.length; i++) {
if (typeof sums[i] !== 'undefined') {
editsummAddOptionToDropdown(dropdown, sums[i]);
}
}
Upvotes: 4
Reputation: 324620
Assuming these are global variables, you can use a loop:
for( var i=1; i<=3; i++) {
if( typeof window['customsum'+i] != "undefined") editsummAddOptionToDropdown(dropdown,window['customsum'+i]);
}
However, it would be advisable to use an array anyway:
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]);
}
Upvotes: 4