9
Actionscript 3 equivalent of PHP's print_r
Oct 14, 2008
Here's a handy little function for easing the development process with Actionscript 3 in Flex and Flash: an equivalent of PHP's recursive print function print_r, which displays objects and arrays in a way that's readable by humans.
Update March 22, 2010: An update of this function has been released.
Code for Flex:
import mx.controls.Alert;
public function pr(obj:*, level:int = 0, output:String = ""):* {
var tabs:String = "";
for(var i:int = 0; i < level; i++, tabs += "\t");
for(var child:* in obj){
output += tabs +"["+ child +"] => "+ obj[child];
var childOutput:String = pr(obj[child], level+1);
if(childOutput != '') output += ' {\n'+ childOutput + tabs +'}';
output += "\n";
}
if(level == 0) Alert.show(output);
else return output;
}
public function test():void {
var obj:Object = new Object();
obj.var1 = "test";
obj.var2 = { var2a: "a", var2b: 10 }
pr(obj);
pr([ "a", "b", "c" ]);
}
Code for Flash:
function pr(obj:*, level:int = 0, output:String = ""):* {
var tabs:String = "";
for(var i:int = 0; i < level; i++, tabs += "\t");
for(var child:* in obj) {
output += tabs +"["+ child +"] => "+ obj[child];
var childOutput:String = pr(obj[child], level+1);
if(childOutput != '') output += ' {\n'+ childOutput + tabs +'}';
output += "\n";
}
if(level == 0) trace(output);
else return output;
}
//Test
var obj:Object = new Object();
obj.var1 = "test";
obj.var2 = { var2a: "a", var2b: 10 }
pr(obj);
pr([ "a", "b", "c" ]);
Both tests will display:
[var1] => test
[var2] => [object Object] {
[var2b] => 10
[var2a] => a
}
[0] => a
[1] => b
[2] => c