Search code examples
flasharraysactionscript-3vectorstrong-typing

How do I initialize a vector with an array of values?


How do I initialize a vector with an array of values?

I tried this and it complies fine, but does not work!

 langs = new Vector.<String>(["en","fr"]);

I also need to load an arbitrary array into a vector, like this:

 langlist = ["en","fr"];
 langs = new Vector.<String>(langlist);

Is there a way to do this?


Edit: How do I initialize a 2D vector with a 2D array of values?

 numbers = [[10,20,30], [10,20,30]];
 nums = Vector.<Vector.<Number>>(numbers);

I tried this but it gives me the error:

TypeError: Error #1034: Type Coercion failed


Solution

  • I don't think that you can pass in an array of arrays into the Vector:

    Vector.<Vector.<Number>>
    

    The type coercion doesn't work for a complex type. If you already have the 2D Array consider the following conversion code:

    var numbers:Array = [[1, 2, 3], [4, 5, 6]];
    var numbersTemp:Array =
    numbers.map(
        function (element:*, index:int, arr:Array):Vector.<Number> {
        return Vector.<Number>(element);
    });
    var nums:Vector.<Vector.<Number>> = Vector.<Vector.<Number>>(numbersTemp);
    

    Of course this will cause new copies of everything to be created twice, so ideally you are not converting big lists.