Kanegasi
Kanegasi

Reputation: 5

Is it possible to condense code to allow multiple variables instead of a line per variable?

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

Answers (2)

Matt Ball
Matt Ball

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions