views:

136

answers:

1

How can I access the member variable of an object by using a variable in the name.

Example:

Entries Object has properties 1, 2, 3, 4, 5. Normally I would access them by

var i : int = Entries.1;
var i : int = Entries.2;

However, if I have a loop

for (var j : int = 1; j < 6; j++){
  trace(Entries[j]);
}

does not work.

 Entries.(j)
 Entries.j

neither.

What's the way to go?

Entries.hasOwnProperty("j")

also does not work to check if the member exists.

Thanks!

+3  A: 
Entries.hasOwnProperty("j")

does not work because you're sending it "j" as a string, you need to convert the integer variable j to a string, therefore representing the number you are looking for. Eg:

Entries.hasOwnProperty(j.toString());

So to extract the property from your object, you can do:

for(var j:int = 1; j < 6; j++)
{
    trace(Entries[j.toString()]);
}
CookieOfFortune
Thanks a lot! I did not that I needed to convert it to a String. Works perfectly now.