Like a lot of people, I use the trace function as my main debugger. It’s great for tracing out numbers or strings, or even arrays of numbers or strings. But when you get into objects, you wind up with something like [object Object], which isn’t too enlightening.
OK, so then we get in to for-in loops, and doing something like this:
for(var prop in myObj){
trace(prop + ": " + myObj[prop]);
}
Again, very useful, but I get sick of typing all that every time. And say one of the properties of myObj is itself and object? You wind up with for-in loops within for-in loops, tedious to type, and you wind up deleting it anyway once you’ve found your bug, or determined it’s not in that object.
So, I made a little recursive function for myself. I have a utils class in my class path, and just added this static method to it:
public static function traceObject(o:Object, recurseDepth:Number, indent:Number):Void {
if(recurseDepth == undefined){
var recurseDepth:Number = 0;
}
if(indent == undefined){
var indent:Number = 0;
}
for(var prop in o){
var lead:String = "";
for(var i=0;i 0){
traceObject(o[prop], recurseDepth-1, indent+1);
}
}
}
Now for any object, myObj, I can just say:
utils.traceObject(myObj);
and I get a nicely formatted output of every property in the object. If I want to recursively trace out the objects two levels down:
utils.traceObject(myObj, 2);
Just be careful about recursing too deeply if your object has references to components, or if you are dealing with a large array of complex objects. I have managed to crash Flash by doing so. 🙂