Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting between an ActionScript Array (Object[]) and a Vector.<Object>

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)?

like image 415
Marty Pitt Avatar asked Nov 30 '10 15:11

Marty Pitt


2 Answers

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

like image 85
Patrick Avatar answered Sep 26 '22 21:09

Patrick


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.

like image 43
Tox Avatar answered Sep 23 '22 21:09

Tox