简体   繁体   中英

How can I refer to a variable using a string containing its name?

Is there a way to refer to a Javascript variable with a string that contains its name?

example:

var myText = 'hello world!';
var someString = 'myText';

//how to output myText value using someString?

You can use an eval to do it, though I try to avoid that sort of thing at all costs.

alert(eval(someString));

A better way, if you find yourself needing to do this, is to use a hash table.

var stuff = { myText: 'hello world!' };
var someString = 'myText';
alert( stuff[someString] );

If that variable is on the global scope, you can use the bracket notation on the global object:

var myText = 'hello world!';
var someString = 'myText';

alert(window[someString]);

Assuming this is at the top level, window[someString] === "hello world!" .

In JavaScript, there is no standard for creating a 'Master Object', or any built-in method to access variables on the initial scope with a string reference that I am aware of.

However, if you are using JavaScript for web development on a browser, the window Object will give you complete access to your current scope. For example:

myVar = "This is my var"; 
if(myVar == window.myVar){
     /*
         This statement would return true
         Because both variables reference
         the same string;
     */
}

This method will allow you to reference any scope-variable WITHOUT making it a string, but you can also use a string as needed with the bracket ( [] ) Selectors.

window['myVar']

It is worth mentioning that keeping data as a variable directly on the current scope leaves it open to be re-defined by other scripts running. Your variable can be overwritten by function argument names, for loop variables, and simply by assigning a new value to that variable.

To overcome this, I suggest using an Object to store all relevant data to your application (Static And/Or OOP). Like this:

$myApp = {
     var1 : 'This is Var1',
     apply : function(){
          alert('Started!');
     }
}

//Referencing relative variables
alert($myApp.var1);

You can do this with eval :

var myText = 'hello world!';
var someString = 'myText';

eval('var theTextInMyText = ' + someString + ';');

alert(theTextInMyText);

The desire to do this at all usually is a "code smell". Perhaps there is a more elegant way...

eval("alert(" + someString + ");");

会工作。

eval will do that:

var myText = 'hello world!!';
var someString = eval('myText');

document.getElementById('hello').innerHTML = someString;

As demonstrated here .

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