Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an array into a string in AS3

I'm relatively new to programming and I was wondering how I would convert an array:

[[0,0,0,0,0,0],
 [1,1,1,1,1,1],
 [2,2,2,2,2,2],
 [3,3,3,3,3,3],
 [4,4,4,4,4,4],
 [5,5,5,5,5,5]];

into a string of comma and line-return delineated indices, like:

"0,0,0,0,0,0
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
4,4,4,4,4,4
5,5,5,5,5,5"

with a dynamic function? I've searched for an implode() function but I couldn't find anything. Thanks in advance!

like image 518
John Jones Avatar asked Oct 07 '09 12:10

John Jones


3 Answers

private function joinArrays(array:Array):String
{
    var result:String = "";
    for each(var a:Array in array)
    {
        result += a.join() + "\n";
    }
    return result;
}

Or if you don't want the line break after the last line:

var result:String = "";
var length:Number = array.length;
for(var i:Number = 0; i < length; i++) 
{
    result += array[i].join();
    if(i != length - 1)
        result += "\n";
}
return result;
like image 187
Amarghosh Avatar answered Oct 14 '22 16:10

Amarghosh


A simple .toString() will do the job !

var a:Array=[[0,0,0,0,0,0],[1,1,1,1,1,1],[2,2,2,2,2,2],[3,3,3,3,3,3],[4,4,4,4,4,4],[5,5,5,5,5,5]];
trace(">",a.toString());
//> 0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,5

EDIT : As often, RegExp will save your soul : )

var a:Array=[[0,0,0,0,0,0],[1,1,1,1,1,1],[2,2,2,2,2,2],[3,3,3,3,3,3],[4,4,4,4,4,4],[5,5,5,5,5,5]];
var columns:int=11;//columns count
trace(a.toString().replace(new RegExp("(.{"+columns+"})(,?)","g"),"$1\n"));
//output :
//0,0,0,0,0,0
//1,1,1,1,1,1
//2,2,2,2,2,2
//3,3,3,3,3,3
//4,4,4,4,4,4
//5,5,5,5,5,5
like image 4
OXMO456 Avatar answered Oct 14 '22 16:10

OXMO456


function join_arr(arr) {
    var newarr = [];
    for (var i = 0; i < arr.length; i++) {
        newarr.push(arr[i].join(","));
    }
    return newarr.join("\n");
}

Haven't tested it but should work :)

like image 1
vava Avatar answered Oct 14 '22 16:10

vava