我有一个数组,其中包含我的一些变量的名称。不要问为什么。 我需要 foreach() 该数组并将其值用作变量名称。 我的变量存在并包含数据。
例子:
myArray = ["variable.name", "variable.age", "variable.genre"];
variable.name = "Mike";
console.log(treat_it_as_variable_name(myArray[0]));
控制台现在应该显示:Mike
在 javascript 中甚至可能吗?
最佳答案
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
可让您评估存储在字符串变量中的完整表达式。
例如(接上一个例子):
var tahir=person;
console.log(eval('person.occupation'));//will print Software Development
console.log(eval('tahir.occupation'));//will print Software Development
在浏览器环境中,顶级变量在 window
对象上定义,因此如果您想访问顶级变量,您可以执行 window[myvar]
关于带有变量名称的javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7092394/