Skip to content Skip to sidebar Skip to footer

Javascript Use Var Value As Name For New Var

How can I use an array key (text value) to reference a variable by that same name? jsFiddle var cr,au,gen,bn,fmt,str; var sbASCtrls = {'cr':'ContentRating','au':'Gold','gen':'Gende

Solution 1:

While you could use eval like this:

// DO NOT DO THIS
eval(key+" = svASCtrls[key];");

You should probably stop and ask yourself why you want to do this in the first place. You already have a very tidy object, so just use it...


Solution 2:

You can define your variables as properties of an object

var obj = { cr: null, au: null, gen: null, bn: null, fmt: null, str: null };
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};

for (var key in sbASCtrls){

    //This does not work ... breaks script
    obj[key] = sbASCtrls[key];

    alert('var CR: ' + obj.cr);
    return false;
}

Solution 3:

As any global variable is a child of the window object, you can create the variable at window[key]

for (var key in sbASCtrls){
    alert("key: " + key);
    alert("val: " + sbASCtrls[key] );

    //This should work, but jsfiddle messes with the window object
    window[key] = sbASCtrls[key];


    alert('var CR: ' + cr);
    return false;
}

Note that this does not work on jsfiddle, but should work on your website.


Post a Comment for "Javascript Use Var Value As Name For New Var"