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

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Marty Pitt
  • 28,822
  • 36
  • 122
  • 195

3 Answers3

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

Tom
  • 12,591
  • 13
  • 72
  • 112
Patrick
  • 15,702
  • 1
  • 39
  • 39
  • Just a reminder, make sure to use the global "Vector.(aObjects)" function, don't use "new Vector.(aObjects)" since the new constructor doesn't work. Took me a second to figure out why this wasn't working for me. – loganjones16 Sep 04 '18 at 14:33
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.

Tox
  • 373
  • 4
  • 13
  • 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. – Lea Cohen Feb 17 '15 at 06:18
0

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

might work.

Francesco
  • 47
  • 1
  • 7
  • Nope, will not work because `myVector` is not an `Array` as `concat()` expects. – Tox Feb 18 '15 at 23:30