Serious Dabbler

Simple Array deepToString in AS3

with one comment

There was a person asking about how to trace nested arrays so the levels of the elements are easily deducible. Eg, if you have an array
[1, [2, 3, 4, [5, 6, [7], 8]], 9, 10] and you call trace on it directly the output will be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, but we want to have the output contain the square brackets as well.

This is very straightforward to implement in an utility function like Java’s Array.deepToString that recurses whenever the next element is an array. However, this means that every time you trace you will have to call that utility function which is quite a bit of extra typing. And, there’s a much easier way than to implement the utility function anyways.

And that is to change the default Array toString behaviour directly. Just include this line somewhere in the start of your project:

Array.prototype.toString = function():String { return "[" + this.join(", ") + "]"; };

This will cause nested arrays like [1, [2, 3, 4, [5, 6, [7], 8]], 9, 10] to trace exactly like that, and if any of the elements are nonprimitive types their toString function will be called. Of course, the downside to this is that every array you trace will be output with the brackets, but I personally do not see how this is in any way inferior to the default way.

And this is not all you can do! You can also easily change it to different formats of your preference to help you in your debugging. Example:

Array.prototype.depth = 0;
Array.prototype.toString = function():String {
    for (var i:int = 0, r:String = "\n" + (this.depth % 5) + ":"; ++i < this.depth; )         r += " ";     r += "[" + this.join(", ") + "]\n";     if (--Array.prototype.depth == 0) return r;     r += (this.depth % 5) + ":";     while (i-->2) r += " ";
    return r;

This outputs the array with higher depths indented more, with each depth colorized differently using FlashDevelop’s colored traces. This example shows that it is very easy to modify the way Arrays are traced to the console by modifying the toString function directly.


Written by jonathanasdf

March 2, 2011 at 7:18 PM

Posted in AS3

Tagged with

One Response

Subscribe to comments with RSS.

  1. hey jonathanasdf i’d like to ask some questions about AS3 can you please email me because i cant fine anyway to contact you i’ve been searching for your email in your blog but no luck. please email me :) Thanks!


    August 1, 2011 at 6:23 AM

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s