简体   繁体   中英

Use string to access variable in javascript

If I have:

name.sub = function() {
    var sub = {};
    var placeholder = "test"
    var test = function() {
        return 42;
    };

    // Desired code would be here

    return sub;
};

I want to use a placeholder to access the variable so that I get 42 .

Something like window["name"]["sub"][placeholder] is seemingly looking for name.sub.test.

The only answers I found were if it was a global variable. Using eval would work, but I've heard it should be avoided where possible.

placeholder = "test"; 
console.log(eval(placeholder + '()'))
// Would return 42

My actual end goal is to have an associative array where:

console.log(array[placeholder]);
// Would return 42

Any help would be appreciated.


This is what I ended up using for anyone interested:

name.sub= function() {
    var sub = {};
    var placeholder = "test"
    var test = function() {
        return 42;

    var newObj = {};
    newObj["test"] = function() {test()}

    console.log(newObj[placeholder]())
    // Should return 42
    };

You can't access variables inside a function from outside said function.

Instead, you could do this:

name.sub = function(placeholder) {
  var functions = {
    "test": function() {
      return 42;
    },
  };
  return functions[placeholder]();
};

name.sub("test"); // 42

I'm not sure if that's what you're looking for but hopefully it is. Explain more?

You can't access local variables inside a function the same way you can access properties of window in global scope.

kangax wrote an interesting article about Understanding delete [in JavaScript] , which includes an explanation of what Activation objects are - which I think is what you're looking for.
I suggest you read the entire article, but long story short:

Inside functions, declared variables (and functions) are added as properties to the activation object of the current scope, as they get added to window in the global scope.
But unlike window :

Note that Activation object is an internal mechanism and is never really accessible by program code.

Conclusion: What you're asking is not (currently) possible.

Your options are limited to:

  1. Using an intermediate object:

     name.sub = function() { var sub = {}; var placeholder = "test"; var array = {}; array.test = function() { return 42; }; console.log(array[placeholder]()); return sub; }; 
  2. Using eval, exactly like you suggested:

     name.sub = function() { var sub = {}; var placeholder = "test"; var test = function() { return 42; }; console.log(eval(placeholder + '()')); return sub; }; 
  3. Using window , by removing var from test 's declaration:

     name.sub = function() { var sub = {}; var placeholder = "test"; test = function() { return 42; }; console.log(window[placeholder]()); return sub; }; 

I suggest the first option for the sake of performance over eval , for compatibility over window (might collide with other code), and simply because of personal taste and what I consider good practice.

By what i understand of your question,

its seem like you are looking for a key/value pair to a JavaScript object literal,

window.name is reserved btw: https://developer.mozilla.org/en-US/docs/Web/API/Window/name

var sub = {
    'test': function() {
        return 42;
    },
    'test2': 42;
}

sub['test']();
sub['test2'];

add by

Using dot notation:
sub.test3 = "value3";

Using square bracket notation:
sub["test4"] = "value4";

Maybe im thinking to simple , but seems like this is what you are looking for

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