I have an array of objects, each of which has a series of x,y properties, like x1,y1,x2,y2,..... now how can I access these dynamically?
Printable View
I have an array of objects, each of which has a series of x,y properties, like x1,y1,x2,y2,..... now how can I access these dynamically?
I assume you know about doing it like this:
I guess you want to access each value through a for loop or some such:Code:array[0].x1 = value;
array[0].x2 = value;
array[0].x3 = value;
...
That code loops through the entirety of the array, then traces the values of each object's first ten x's and y'sCode:for (i=0;i<array.length;i++) {
for (n=0;n<10;n++) {
trace(array[i]["x"+n]);
trace(array[i]["y"+n]);
}
}
You might have seen code where people use
instead ofCode:_root["object"+1]._y
My code above uses the same basic method.Code:_root.object1._y
Hope this helps :)
I did try that already, but for some reason i am getting "undefined"....that's the reason I asked this! On a side note, is it possible to get the length or number of properties of the object for use in the for loop?
I've tried it and it doesn't give me undefined. Have you tried manually accessing it to check that it isn't really undefined? Perhaps you can post up some of your code so I can have a look.
I don't know of any way to count the number of properties. Not sure exactly what your trying to do but it might be a good idea to have an array instead of lots of properties.
It might make things a bit easier for you :)Code:object.xArray = [0,0,0];
object.yArray = [2,2,2];
actually I would need to let the player reference values in game with a name(think a mini programming simulator), so objects work best in my case! And I have no idea why I got the undefined thing....but the same code gives this problem in flashcs4, and works perfectly when I compile it in flex SDK+ Flashdevelop!
Also the statement I use for checking is: trace(arr[i].x1+" : "+arr[i]["x"+1]),
Ah in that case the problem might be to do with AS3. Not sure, though, having never used AS3 myself.
flex and flash both are as3 actually....just some features and implementations are a bit different
Just shooting a blank here, but have you tried this?
Code:var theObject = arr[i]
theObject["x"+j]
oookay...this one works in both cs4 and fd.....but why?
Yeah weird. Guess the Flash compiler treats arrays differently then Flex'