15

Are there options for converting an Array to a Vector in ActionScript without iterating the array?

What about the other way (converting a Vector to an Array)?

3 Answers 3

26

For the Array to Vector, use the Vector.<TYPE>() function that accept an array and will return the vector created :

var aObjects:Array = [{a:'1'}, {b:'2'}, {c:'3'}];
// use Vector function
var vObjects:Vector.<Object> = Vector.<Object>(aObjects);

For the other there is no builtin function, so you have to do a loop over each Vector item and put then into an Array

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

1 Comment

Just a reminder, make sure to use the global "Vector.<Object>(aObjects)" function, don't use "new Vector.<Object>(aObjects)" since the new constructor doesn't work. Took me a second to figure out why this wasn't working for me.
2
vObjects.push.apply(null, aObjects);

And another way to do it.

The trick here is simple. If you try to use the concat() method to load your array into a vector it will fail because the input is a vector and instead of adding the vector elements AS will add the whole vector as one entry. And if you were to use push() you'd have to go through all items in the array and add them one by one.

In ActionScript every function can be called in three ways:

  • Normal way: vObjects.push(aObjects)

    Throws error because aObjects is not an Object but an Array.

  • The call method: vObjects.push.call(this, myObject1, myObject2, ..., myObjectN)

    Doesn't help us because we cannot split the aObjects array into a comma-separated list that we can pass to the function.

  • The apply method: vObjects.push.apply(this, aObjects)

    Going this route AS will happily accept the array as input and add its elements to the vector. You will still get a runtime error if the element types of the array and the vector do not match. Note the first parameter: it defines what is scoped to this when running the function, in most cases null will be fine, but if you use the this keyword in the function to call you should pass something other than null.

1 Comment

If you could please edit your answer and explain what the code you're showing does, and why/how that code answers the question, it could really help.
0

var myArray:Array = [].concat(myVector);

might work.

1 Comment

Nope, will not work because myVector is not an Array as concat() expects.

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.