简体   繁体   English

使用字符串访问变量

[英]Using a string to access a variable

I currently have a Javascript function that uses a string to reference an object name and acces its properties. 我目前有一个Javascript函数,它使用字符串来引用对象名称并访问其属性。 I'm currently using eval() to get the the desired effect which I know is very, very wrong. 我目前正在使用eval()来获得所需的效果,我知道这是非常非常错误的。 Here is an example of how I'm currently achieving what I want: 这是我目前如何实现我想要的一个例子:

var stringToObjectRef = function() {

    var myTestVar = "myTestObject";
    var myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };

    var myValue = eval(myTestVar + '.item1');

    alert(myValue);

}();

I've tried using something like [myTestVar].item1, but this returns undefined. 我尝试过使用像[myTestVar] .item1这样的东西,但这会返回undefined。 What is the correct syntax to achieve this? 实现此目的的正确语法是什么?

Thanks in advance. 提前致谢。

If you're talking about the item1 part, you're looking for: 如果您正在谈论item1部分,那么您正在寻找:

myValue = myTestObject["item1"];

No need for eval . 不需要eval (There almost never is.) (几乎从来没有。)

If you're talking about getting at the myTestObject variable using a "myTestObject" string, you want to refactor the code so you're not doing that, rather than using eval . 如果您正在讨论使用“myTestObject”字符串获取myTestObject变量,那么您希望重构代码,这样您就不会这样做,而不是使用eval Unfortunately the variable object used for symbol resolution within the function is not accessible directly. 遗憾的是,函数中用于符号解析的变量对象无法直接访问。 The refactor could just use an object explicitly: 重构可以只显式使用一个对象:

var stringToObjectRef = function() {

    var objects = {};

    var myTestVar = "myTestObject";
    objects.myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };

    var myValue = objects[myTestVar].item1;

    alert(myValue);

}();

Off-topic, I don't recall precisely why, but if you're going to execute that anonymous function immediately like that, you need to put the function expression in parentheses: 偏离主题,我不记得究竟为什么,但如果你要立即执行那个匿名函数,你需要将函数表达式放在括号中:

var x = (function() { return 5; })();

rather than 而不是

var x = function() { return 5; }();

Again, I don't recall why, and whether it was because of an implementation bug in a popular interpreter or an actual requirement of the syntax. 同样,我不记得为什么,以及是否是因为流行的解释器中的实现错误或语法的实际要求。

Try this instead: 试试这个:

var stringToObjectRef = function() {
  var myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };
  var myValue = myTestObject['item1'];
  alert(myValue);
}();

eval("myTestObject[\\"item1\\"") should do the trick, as myTestObject.item1 is shorthand for myTestObject["item1"] eval(“myTestObject [\\”item1 \\“”)应该可以解决问题,因为myTestObject.item1是myTestObject [“item1”]的简写

How do I reference an object dynamically? 如何动态引用对象?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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