Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get local variable by its name in JS?

Tags:

javascript

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]);
}
like image 876
klesh Avatar asked Oct 15 '22 10:10

klesh


1 Answers

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));
}
like image 54
YOU Avatar answered Nov 10 '22 01:11

YOU