开发者

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

Are there options for c开发者_JAVA技巧onverting an Array to a Vector in ActionScript without iterating the array?

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


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


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.


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

might work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜