0

How can I create dynamic variable in ActionScript?

Example code:

import windows.nwindow;

for(var num:int = 0; num< 2; num++)
            {
                this["nWin"+num] = new nwindow();
                this["nWin"+num].width = 320;
                this["nWin"+num].height = 200;
                this["nWin"+num].title="window" + num;
                this["nWin"+num].open();
            }

When I run the above code it dispatch this error:

Error #1056: Cannot create property nWin0 on MultiWindow.

So, how can I use dynamic variable for this case here?

1
  • The answer below is correct, but I'm wondering what is the advantage in your program to having a dynamic member vs. an element in an array. I.e., rather than this["nWin"+num], have this.myWindows[num]? Commented Dec 13, 2013 at 16:26

1 Answer 1

1

you can use a dictionary to achieve this. eg-

        var dict:Dictionary = new Dictionary;
        for(var num:int = 0; num< 2; num++)
        {
            var str:String = "nWin"+num;
            dict[str] = new nwindow();
            dict[str].width = 320;
            dict[str].height = 200;
            dict[str].title="window" + num;
            dict[str].open();
        }
Sign up to request clarification or add additional context in comments.

1 Comment

In this case an "Object" would have been enough. Dictionaries are used wherever the key is not a string. If however your key can be mapped to strings I guess an Object should be simpler.

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.