2D Array to String

function format2D(a:Array):String {
	var str:String="[";
	for (var i:int = 0; i<a.length; i++) {
		str+="["+a[i].toString()+"],";
	}
	str=str.substr(0,str.length-1);
	str+="]";
	return str;
}

// test it out
var array2D:Array = [[1,2,3], [4,5,6], [7,8,9]];

trace(array2D);
trace(format2D(array2D));

/* outputs:
1,2,3,4,5,6,7,8,9
[[1,2,3],[4,5,6],[7,8,9]]

*/

When you trace a 2D array to the output window the actual structure of the array isn’t clear. For some reason it just appears as a 1D array – this small function fixes that problem – it could also be used to save 2D arrays to text files etc…

Leave a Reply

Your email address will not be published. Required fields are marked *