Jason Castillo Jason Castillo - 1 month ago 5
Javascript Question

check if [variable name] + [number] exists?

I'm using the code below to check if var1 exists, then assigning another variable (promt) to store var1 provided that the user types in the variable. Problem is I have about twenty variables I need to check so my code looks like the below times ten:

if (typeof var1 !== 'undefined') {
if(selection==var1){
var promt = var1;
}
}
if (typeof var2 !== 'undefined') {
if(selection==var2){
var promt = var2;
}
}


This (a) makes a ton of inefficient code and (b) may cause errors if I have over twenty variables.
Is there a way to check if var1, var2, var3, etc.. exists then stop checking when the variables stop?
The goal is to be able to have one hundred variables and still have the same amount of code I would have if there were two.

Answer

If your variables are fields on an object you can easily build the field names dynamically:

fieldname = 'var' + index;
if (typeof obj[fieldname] !== 'undefined') {
    if (selection == obj[fieldname]){
        var promt = obj[fieldname];
    }           
}

For local variables I however can't provide a solution.

Comments