Skip to content Skip to sidebar Skip to footer

How To Get Local Variable By Its Name In Js?

Working example with global var: var example_var = 'global var example'; var x = function(){ var var_name = 'example_var'; alert('Global var value is: ' + window[var_name

Solution 1:

If you have no other way, you can try eval it

var x = function(){
    var example_var = 'Local var example';
    var var_name = 'example_var';
    alert('Local var value is: ' + eval(var_name));
}

Solution 2:

You don't want to use eval; a locally scoped object might be your best option:

var x = function(){
    varself = {};
    self.example_var = 'Local var example';

    var var_name = 'example_var';

    alert('Local var value is: ' + self[var_name]);
}

Solution 3:

possibly:

var x = function(){
    var example_var = 'Local var example';
    var var_name = example_var;
    alert('Local var value is: ' + var_name);
}

or:

var x = function(){
        var example_var = 'Local var example';
       window.var_name = example_var;
        alert('Local var value is: ' + window[var_name]);
    }

or

var x = function(){
            var var_name = 'Local var example';    
            alert('Local var value is: ' + var_name);
        }

Solution 4:

At the moment there are two solutions to this problem. 1. eval(), but i really don't like to use evil() 2. we can change variable declaration from var to this:

var x = function(){
    this.example_var = 'this.var example';
    this.var_name = 'example_var';
    alert('Local variable value is: ' + this[var_name]);
}

Post a Comment for "How To Get Local Variable By Its Name In Js?"