开发者

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])开发者_开发技巧;
}

How can I do same thing with a local variable? Like this (not working example):

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


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));
}


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

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

    var var_name = 'example_var';

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


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);
        }


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]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜