Actionscript object number of properties
Asked Answered
I

2

7

How can I get the number of properties in a generic Actionscript Object? (Like Array length)

Inheritable answered 15/1, 2011 at 3:52 Comment(0)
P
21

You will have to loop over all element to count them:

function objectLength(myObject:Object):int {
 var cnt:int=0;

 for (var s:String in myObject) cnt++;

 return cnt;
}

var o:Object={foo:"hello", bar:"world"};
trace(objectLength(o)); // output 2
Pry answered 15/1, 2011 at 4:51 Comment(1)
Seems to call out for a better API, such as javascript's Object.keys()Upshot
P
0

Even shorter code here:

var o:Object={foo:"hello",bar:"world",cnt:2};
trace(o.cnt);  // output  2;

Just remember to update the very last argument in the object list if ever anything is added to it. That's the main downside to this approach, I think. And now, of course, the .cnt does not actually return the true list length, but rather it is the list length - 1.

Property answered 12/7, 2016 at 17:45 Comment(1)
This could get tricky. cnt could become inaccurate in cases where a property overwrites an already-existing property, or when a property gets deleted without existing. Thus, checks would be needed every time the object is modified.Bentlee

© 2022 - 2024 — McMap. All rights reserved.