6

I need to set custom variable name for every iteration. Why this isn't possible?

for (var i:uint = 0; i < 50; i++)
{
   var ['name' +i] = new Sprite();
}
*//1840: Syntax error: expecting identifier before left bracket*
0

3 Answers 3

9

You want to use a hash map to do this.

var map:Object = {};
for (var i:uint = 0; i < 50; i++)
{
   map['name' +i] = new Sprite();
}

Otherwise you're confusing the compiler. Dynamic names for local variables aren't allowed.

Sign up to request clarification or add additional context in comments.

2 Comments

This is what I was looking for, but it doesen't work in my scenario. I will just have to use an Array. Itis very poorly documented on livedocs, do maybe know any decent elaboration?
You can use an array as well. Or you can iterate over the map like an array. (for (var n:String in map){}). Maybe you can elaborate on why you need to do this and we can suggest alternatives.
3

There is sort of a way around this, depending on what you're doing. If these clips are all added to stage then you can use the getChildByName method to access them. Your setup would look something like this:

var clips:Array = [];

for (var i:int = 0; i < 100; i++) {
    clips[i] = new MovieClip();
    clips[i].name = "clip" + i;
    addChild(clips[i]);
}

trace (getChildByName("clip2")); // traces [object MovieClip]

This is done by querying the display API, though, so you can't use getChildByName on anything that's not added to a display list somewhere.

Hope that helps!

Comments

0

Though not recommended as dynamic classes are slower than sealed classes, you can certainly make the class dynamic and then use this["varname"] to set the variable. You need to specify a class as dynamic even when extending a dynamic class like Movieclip (sub classes don't inherit this).

dynamic public class MyClass{
....
....
....
for (var i:uint = 0; i < 50; i++)
{
   this['name' +i] = new Sprite();
}

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.