简体   繁体   中英

How to access variables inside function based on string variable representation

I have following function

function myFunction(){
var foo="My Foo String";
}

I would like to access my variable in a following way

function myFunction(){
var foo="My Foo String";
console.log(SOMETHINGIDONOTKNOWABOUT["foo"]);
}

I know in javascript its possible to use window["yourvariablename"] to access it, but I am interested to access function variable in similar way, therefor Is there a way to access a javascript variable using a string that contains the name of the variable? is not a duplicate. Eval is not correct answer for me.

Don't do this. Dynamic variables are really annoying to debug and optimize by the browser.

Use a set, a map, create a class for it, or even a simple object to store things you want to be able to access with a string.

function myFunction() {
    var myData = {
        "foo": "My foo string"
    };
    console.log( myData[ "foo" ] );
}

If I understand you question properly, you should use foo without quotes:

window[foo]

Just note that putting values on the global scope is a bad practice.

Is the following snippet the kind of things you are trying to achieve?

If you want to use a variable as an array element name, you don't have to use quotes. ie array["foo"] should be array[foo] if foo is a variable.

 var array = []; array['foo'] = 'bar'; // Code #1 function myFunction(element) { console.log(array[element]); } myFunction('foo'); // Code #2 function myFunction() { element = 'foo'; console.log(array[element]); } myFunction(); 

Hope it helps, in any way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM