views:

790

answers:

2

I'm trying to understand how this piece of code from Keith Peter's Advanced Actionscript works. Essentially there's a for loop going on to split key/value pairs seperated by :. Here's the code:

var definition:Object = new Object();
for(var i = 0;i < tokens.length; i++)  
{
    var key:String = tokens[i].split(":")[0];
    var val:String = tokens[i].split(":")[1];
    definition[key] = val;
}

And tokens is an array of strings containing values such as:

["type:GraphicTile", "graphicClass:MapTest_Tile01"]

The thing I can't understand is, what is the significence of "[0]" and "[1]". How does [1] indicate that the String val is to hold the data after the ":" split(the value, like "GraphicTile" or "MapTest_Tile01"), and [0] pointing to the data before the split(keys like "type" or "graphicClass"). Adobe's Actionscript reference doesn't list any parameters that can be passed to the Array.split method using square brackets like this.

+1  A: 

The split() method is returning an array of the tokens created by splitting the string. This array is then being indexed with [0] and [1] to get the first and second members. It's exactly the same as tokens[i] being used to access the ith member of the tokens array.

Nick Lewis
Thanks! I guess I was looking at it the wrong way.. I thought the parameters being passed in the square brackets were being passed to the split method, rather than being used to access values in the array returned.Loving the community here, you guys are very helpful!
Qasim
A: 

nick gave the correct answer ...

as CookieOfFortune implicitely pointed out, the code is not really good ...

var definition:Object = new Object();
for(var i = 0;i < tokens.length; i++)  
{
    var parts:Array = tokens[i].split(":");
    var key:String = parts[0];
    var val:String = parts[1];
    definition[key] = val;
}

this would avoid splitting the String twice ... also maybe it makes clearer what happens ...

back2dos