0

This seems silly to ask this, but is there a way to make an associative array in actionscript right in the variable declarations?

e.g.

private var stages:Array = [
    "name" : "NY Stage",
    "location" : "New York",
    "capacity" : 15000
]

Instead, the way I'm doing it is (1): declaring the array up top and then creating the rest of the array in the class constructor:

private var stages:Array;

public function PlayStage(){
    stages["name"] = "NY Stage";
    stages["location"] = "New York";
    stages["capacity"] = 15000;
}

Can I do something like the top (without creating an object)?

2 Answers 2

3

Don't use Array to create an associative array. If you read the Array documentation, it specifically recommends against the practice.

Use an Object instead. Here's a link to the documentation on how to create associative arrays:

Associative arrays in AS3

To iterate over the keys of an associative array (this would be used to get the length as well), you can use this:

var oObj:Object = { "name" : "pear", "color" : "yellow" };

...

for ( var key:* in oObj )
{
    // do something with the key or increment a counter, etc.
}
Sign up to request clarification or add additional context in comments.

3 Comments

ah, I see. i also see that object doesn't have any methods like arrays (slice, splice, length), which is why i was hoping to use associative arrays (instead of turning objects into arrays when needed or looping). what's the easiest way to get the length of an object's properties?
@Prodikl I updated my answer with a small for loop that you can use to iterate over the keys. You can use this method to create a function that returns the length of an associative array that you pass in.
that's awesome, thanks! and accessing the value would just be oObj[key], right?
1

Like xxbbcc said, Associative arrays are essentially objects in AS3, so the shorthand object construction will work:

private var stages:Object = {
    "name" : "NY Stage",
    "location" : "New York",
    "capacity" : 15000
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.