Is dynamic variable naming like this possible in ActionScript 3?
for (var xz=0;xz<10;xz++){
var this['name' + xz]:Number = xz;
}
Is dynamic variable naming like this possible in ActionScript 3?
for (var xz=0;xz<10;xz++){
var this['name' + xz]:Number = xz;
}
Yes, it sure is - AS3 comes from ECMA script, so this is setting a property to an object (in this case it's this
). So you can dynamically set properties. But you are a little bit wrong about how to do it - there is no need to use var
, because you don't declare it, you set it. It's like using:
this.propertyName = 'value';
From now on, this
will have propertyName
equal to 'value
'. Therefore you should just use:
this['name' + xz] = xz;
That's all!
Edit: as BotMaster mentioned - if you are using classes and you want to dynamically add properties, the class must be set as dynamic. Most of the commonly used ones are already dynamic (as Aaron mentioned :)). I didn't go into much details as I think you simply need to do this on your timeline. If not - please specify this in your question so that you can get more accurate answer than this one. The same goes if your new property needs to be typed (can't think of any point wanting this) - you should see BotMaster's answer :)
You should use an array for this kind of list of variables. While you can create properties dynamically, you usually want to avoid it. Especially in your case, where the actual identifier of each variable is not a
String
, but a number. So why not use something that does exactly that: identify its elements by a number? And that's exactly what an array does.code example: