5

How can add element to array in ActionScript3

If i have an array:

var myArray:Array;

How can add element to this array "myArray", something like this:

myArray[] = value;

My second question is: How can compare if variable value exist in array element value?

Something like in_array function in php

5
  • It's roughly the same in ActionScript as in JavaScript. Commented Jul 10, 2011 at 21:21
  • 1
    livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html Commented Jul 10, 2011 at 21:24
  • My second question is: How can compare if variable value exist in array element value? Something like in_array function in php Commented Jul 10, 2011 at 21:26
  • 1
    Voted to close. User did not do any research before asking question. Commented Jul 11, 2011 at 14:36
  • @Faraona can you change the accepted answer to the highly upvoted one? I'd like to remove my answer but cannot because it is the accepted answer. While my answer isn't incorrect, it isn't as complete and people are inappropriately using downvotes to express that the other answer is better. Commented Sep 1, 2015 at 12:32

2 Answers 2

28

1. All of these are different ways of adding item to array.

  • someArray.push(someValue); : add last item
  • someArray.unshift(someValue); : add first item
  • someArray[index] = someValue; : set item somewhere
  • someArray.splice(index, 0, someValue); : insert item somewhere

2. Checking if a value is present in array.

if (someArray.indexOf(someValue) == -1) { /*value is not present*/ }

Refer to ActionScript language reference on Adobe livedocs.

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

2 Comments

Thanks. Comprehensive, but brief.
Nate... indexOf.. IS looping. Inside indexOf, the VM is doing a loop. How else would it know what the index of an item is? Magic?
4

To answer both your questions here, you can add to an array by direct access or by the push() method, like so:

myArray[7] = something;

or

myArray.push(something);

Also as Nox noted, you can use the splice method as well to add in elements. This method is used to delete N amount of elements at a specific index, but you can also simultaneously inject one or more elements at the same index.

For your second question about how to check values or compare them in an array, here is one method:

var i:int = 0;

for(i; i < myArray.length; ++i){
    if(myArray[i] == 10){
       trace('found');
    }
}

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.