0

Is this possible? For example, if I had 100 items named item1.....item100, could I add them all to an array using a loop? Something along these lines....but this doesn't work obviously:

for (var i:int = 1; i <= 100; i++)
{
     myArray.push("label" + 1);
}

Luckily I only have 10 items, so I can do it manually, but I'm just curious for future reference...

Thanks!

4 Answers 4

1

The array access operator will let you reference properties and objects by name like that, so if you have:

myArray.push(label1);

You can use this instead:

myArray.push(this["label" + 1]);
Sign up to request clarification or add additional context in comments.

1 Comment

In a for loop as you've done you would of course use the iterator. I'm just illustrating equivalent references though.
1

Depends on on you mean by "items".

If they are properties of the current class use:

for (var i:int = 1; i <= 100; i++)
{
    myArray.push(this["label" + i]);
}

1 Comment

Also, correct! Thanks! I'll give you a vote up as soon as I get enough rep :D Edit: Done!
0

You can do this even if the names of the objects do not follow any particular pattern but they have to be inside a 'container' (you will add all objects from the container to the array):

for (var i:int = 0; i < containerName.numChildren; i++)
{
    myArray.push(containerName.getChildAt(i);
}

Comments

0

You have to get the link to the object instance to push it into the array, for example if the names of your text fields are label1, label2, etc. you can use the following code:

for (var i:int = 1; i <= 100; i++)
{
     myArray.push(labelsContainer.getChildByName("label" + i));
}

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.