开发者

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开发者_StackOverflow社区 use the values of it as variables names. 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

Is it even possible in javascript?


Javascript let's you access object properties dynamically. 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.

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]


You can use eval(myArray[i]) to do this. Note that eval() is considered bad practice.

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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜