Javascript:将字符串解释为对象引用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10953303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:45:15  来源:igfitidea点击:

Javascript: interpret string as object reference?

javascript

提问by chris_mac

Possible Duplicate:
Javascript use variable as object name

可能重复:
Javascript 使用变量作为对象名称

How do I get JS to treat a string as a reference to a previously defined object? Simplified:

如何让 JS 将字符串视为对先前定义的对象的引用?简化:

var myObject = new MyObject();

var myString = "myObject";

var wantThisToWork = myString.myproperty;

回答by Juan Mendes

If the variable is in the global scope, you can access it as a property of the global object

如果变量在全局范围内,则可以将其作为全局对象的属性进行访问

var a = "hello world";
var varName = "a";
console.log( window[varName] ); // outputs hello world
console.log( this[varName] ); // also works (this === window) in this case

However, if it's a local variable, the only way is to use eval(disclaimer)

但是,如果它是局部变量,则唯一的方法是使用eval免责声明

function () {
  var a = "hello world";
  var varName = "a";
  console.log( this[varName] ); // won't work
  console.log( eval(varName) ); // Does work
}

Unless you can put your dynamic variables into an object and access it like a property

除非您可以将动态变量放入对象并像访问属性一样访问它

function () {
  var scope = {
    a: "hello world";
  };
  var varName = "a";
  console.log( scope[varName] ); // works
}

回答by Parth Thakkar

The only way, as it seems to me, would be to use eval. But as they say, eval is evil - but not in controlled environments. This is the way it is possible, but i don't recommend using eval, unless it is absolutely necessary.

在我看来,唯一的方法是使用 eval。但正如他们所说, eval 是邪恶的——但不是在受控环境中。这是可能的方式,但我不建议使用 eval,除非绝对必要。

var myObject = new MyObject();
var myString = "myObject";
var wantThisToWork = eval(myString).myproperty;

回答by sachleen

You can use the evalfunction.

您可以使用该eval功能。

eval(myString).myproperty

Careful with eval, though, if this is something the user is inputting, it will execute any javascript code!

但是,小心使用 eval,如果这是用户输入的内容,它将执行任何 javascript 代码!

回答by Anand

Use eval()

使用eval()

var myObject = {};
myObject.myproperty = "Hello";
var myString = "myObject";

var wantThisToWork = eval(myString).myproperty;