带有变量名称的javascript数组

标签 javascript arrays variables

我有一个数组,其中包含我的一些变量的名称。不要问为什么。 我需要 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/

相关文章:

javascript - innerHtml 前置文本而不是追加

javascript - 删除表中的列 javascript

java - 打印数组列表中的内容

c - 如何知道 C 中数组中元素的确切数量?

sql - Coldfusion - 循环访问数据库查询结果时的可变字段名称

javascript - 我只需要使用 JQuery 的 Live 绑定(bind)到我的元素一次

javascript - innerHTML 更改后 HTML 上传表单重置

javascript - 我在 JavaScript 中遇到了未定义的问题,并且不明白为什么

variables - Tensorflow中默认的variable_scope是什么?

java - 对于循环整数和字符串变量?