简体   繁体   English

具有变量名称的 javascript 数组

[英]javascript array with names of variables

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.我需要 foreach() 该数组并将其值用作变量名称。 My variables exists and contain data.我的变量存在并包含数据。

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 甚至有可能吗?

Javascript let's you access object properties dynamically. Javascript 让您动态访问 object 属性。 For example,例如,

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 object 上定义,所以如果你想访问顶级变量,你可以做window[myvar]

You can use eval(myArray[i]) to do this.您可以使用eval(myArray[i])来执行此操作。 Note that eval() is considered bad practice.请注意, 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]]);
}

You could parse the variable yourself:您可以自己解析变量:

var t = myArray[0].split(".");
console.log(this[t[0]][t[1]]);

See this question for how to get hold of the gloabal object and then index into that:有关如何获取全局 object 的信息,请参阅此问题,然后对其进行索引:

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.您需要将它们解析为以点分隔的部分,并一次对一个链接进行索引。

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

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