views:

43

answers:

2

hello,

in PHP i am used to create a array with using names as keys like

array["something1"] = "output1";
array["something2"] = "output2";
array["something3"] = "output3";

and then use foreach to let them print or do other things with it like

foreach ($array as $key => $value) {
echo "$key = $value";
}

is there something similar possible in AS3?

EDIT:: what also is handy of these vars is that you can do something like this:

GetSomethingString:String = GetTheString(); // lets yust say this returns something2
trace(array[GetSomethingString]); // then this will return output2
+2  A: 

What you want is an object and a for ... in statement:

var obj = {'something1': 'output1',
           'something2': 'output2',
           'something3': 'output3'};
for (var key:String in obj){
    trace(key + '=' + obj[key]);
}

EDIT: yes, this also allows:

trace(obj[getTheString()]);
Chadwick
+1. Just a note. `key` is always a `String` in a `for...in` loop so there's no need for `*`. Also, as opposed to PHP, the order in which elements are traversed is not guaranteed to be the same as you might expect based on insertion order (not that you implied this in your answer)
Juan Pablo Califano
@JuanPabloCalifano correct on both accounts. I updated for the key type, but there's not much that can be done about the ordering - it's entirely implementation dependent (e.g. flex, vs rhino, vs Chrome's javascript impl, etc...)
Chadwick
+1  A: 

Using an object will in fact work, but I think what you're actually looking for is the Dictionary class; see this link

Zev