Javascript 带有变量名称的javascript数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7092394/
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
javascript array with names of variables
提问by Leth
I have an array with the name of some of my variables. Don't ask why. I need to foreach() that array and use the values of it as variables names. My variables exists and contain data.
我有一个数组,其中包含一些变量的名称。不要问为什么。我需要 foreach() 该数组并将其值用作变量名称。我的变量存在并包含数据。
Example:
例子:
myArray = ["variable.name", "variable.age", "variable.genre"];
variable.name = "Mike";
console.log(treat_it_as_variable_name(myArray[0]));
Console should now display: Mike
控制台现在应该显示:Mike
Is it even possible in javascript?
在javascript中甚至可能吗?
回答by Tahir Akhtar
Javascript let's you access object properties dynamically. For example,
Javascript 让您可以动态访问对象属性。例如,
var person = {name:"Tahir Akhtar", occupation: "Software Development" };
var p1="name";
var p2="occupation";
console.log(person[p1]); //will print Tahir Akhtar
console.log(person[p2]); //will print Software Development
eval
on the other hand lets you evaluate a complete expression stored in a string variable.
eval
另一方面,让您评估存储在字符串变量中的完整表达式。
For example (continuing from previous example):
例如(从前面的例子继续):
var tahir=person;
console.log(eval('person.occupation'));//will print Software Development
console.log(eval('tahir.occupation'));//will print Software Development
In browser environment top level variables get defined on window
object so if you want to access top level variables you can do window[myvar]
在浏览器环境中,顶级变量在window
对象上定义,因此如果您想访问顶级变量,您可以这样做window[myvar]
回答by cdhowie
You can use eval(myArray[i])
to do this. Note that eval()
is considered bad practice.
您可以使用它eval(myArray[i])
来执行此操作。请注意,这eval()
被认为是不好的做法。
You might consider doing something like this instead:
你可能会考虑做这样的事情:
var myArray = ["name", "age", "genre"];
var i;
for (i = 0; i < myArray.length; i++) {
console.log(variable[myArray[i]]);
}
回答by hmakholm left over Monica
See this questionfor how to get hold of the gloabal object and then index into that:
请参阅此问题以了解如何获取全局对象,然后对其进行索引:
var global = // code from earlier question here
console.log(global[myArray[0]])
Hmm... I see now that your "variable names" contain dots, so they are not actually single names. You'll need to parse them into dot-delimited parts and do the indexing one link at a time.
嗯......我现在看到你的“变量名”包含点,所以它们实际上不是单个名称。您需要将它们解析为点分隔的部分,并一次对一个链接进行索引。
回答by laurent
You could parse the variable yourself:
您可以自己解析变量:
var t = myArray[0].split(".");
console.log(this[t[0]][t[1]]);