Search code examples
javascriptdynamic-variables

["var"+1]=someValue - Can something like this be done?


function giveValue(n){
    ["r"+n]=5;
}
giveValue(10);

You get the idea.

The point is that I have a handful of variables with similar name, varying only in a number at the end. Using a switch statement is fine with a few variables a few times, but for this particular project it is driving me crazy. I know I can do:

var r2="lol";
var someVar=eval("r"+2);
//someVar=="lol"

And I was wondering if I can do something like this but with the dynamic reference to the left of an assignment.

Is it possible?


Solution

  • If you REALLY want to do that, this should work:

    function giveValue(n){
        window['r'+n] = 5;
    }
    giveValue(10);
    
    console.log(r10)
    

    But please, DON'T DO IT!

    You really should use arrays!