2D Array to String

Actionscript:
  1. function format2D(a:Array):String {
  2.     var str:String="[";
  3.     for (var i:int = 0; i<a.length; i++) {
  4.         str+="["+a[i].toString()+"],";
  5.     }
  6.     str=str.substr(0,str.length-1);
  7.     str+="]";
  8.     return str;
  9. }
  10.  
  11. // test it out
  12. var array2D:Array = [[1,2,3], [4,5,6], [7,8,9]];
  13.  
  14. trace(array2D);
  15. trace(format2D(array2D));
  16.  
  17. /* outputs:
  18. 1,2,3,4,5,6,7,8,9
  19. [[1,2,3],[4,5,6],[7,8,9]]
  20.  
  21. */

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...

This entry was posted in string manipulation, strings and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*