Jason Castillo Jason Castillo - 1 year ago 74
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') {
var promt = var1;
if (typeof var2 !== 'undefined') {
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download