Array.toString

I was recently trying to debug some code that returned an array of arrays. In Actionscript and seemingly most (if not all) ECMAScript implementations, when calling toString on an array object it passes back a comma separated list of elements in the array. This is no good if you have nested arrays because:

    [1, 2, 3, [1, 2, 3]].toString();

…returns:

    "1, 2, 3, 1, 2, 3"

So it appears as a flat array, whereas the underlying object is something entirely different. So if you happen to be quickly debugging using trace (ActionScript) or alert (JavaScript) the object can appear to be something it is not.

If you want the Array object to return a string of comma separated elements contained in square braces then run this snippet somewhere before you start creating new Array objects:

    Array.prototype._toString = Array.prototype.toString;
    Array.prototype.toString = function() {return '[' + this._toString() + ']';}

Now:

    [1, 2, 3, [1, 2, 3]].toString();

…returns:

    "[1, 2, 3, [1, 2, 3]]"

Much better!