AS3: Как преобразовать Вектор в Массив

используйте $ get и $ lt, чтобы найти данные даты в mongodb

var tomorrowDate = moment(new Date()).add(1, 'days').format("YYYY-MM-DD");
db.collection.find({"plannedDeliveryDate":{ $gte: new Date(tomorrowDate +"T00:00:00.000Z"),$lt: new Date(tomorrowDate + "T23:59:59.999Z")}})
23
задан Dan Homerick 10 July 2009 в 05:12
поделиться

6 ответов

ваш подход самый быстрый ... если вы думаете, что он многословный, тогда создайте служебную функцию ... :)

edit:

Чтобы создать служебную программу функция вам, вероятно, придется отбросить тип следующим образом:

function toArray(iterable:*):Array {
     var ret:Array = [];
     for each (var elem:Foo in iterable) ret.push(elem);
     return ret;
}
24
ответ дан 29 November 2019 в 02:16
поделиться

используйте:

var myArray:Array = [];
myArray.push.apply(null, myVector);

или

var myArray:Array = new Array().concat(myVector);
6
ответ дан vaukalak 29 November 2019 в 02:16
поделиться

Второй ответ Ваукалака не только работает, но и намного быстрее, чем ответ с верхним голосом, я его немного помассировал, так как [] дает значительно более быстрое построение массива, чем новый Array (). Ниже также приведен лучший способ создания вектора из массива.

// make a Vector from an array
var toVector : Vector.<String> = Vector.<String>(['a','b','c']) 

// populate an array from a Vector
var toArray : Array = [].concat(toVector);

Обратите внимание, что похоже, что это работает только со вспышкой 11

3
ответ дан Paul At Work 29 November 2019 в 02:16
поделиться

There is a function called forEach which both Vector and Array has which you can use. Basically it calls a function for each element in the vector. This is how it works:

var myVector:Vector.<Foo> = new Vector();
var myArray:Array = [];

myVector.forEach(arrayConverter);

function arrayConverter(element:*, index:int, array:Array):void{
    myArray[myArray.length] = element;
}

But I couldn't find a function which just moves all the values from the Vector to an Array. Another solution could be that you create a class which extends the Vector class and then you have a public function called toArray() and then you have that code in that function so you don't have to write it each time you want to convert.

Vector documentation

Edit: Found this old question today and thought it would be interesting to do a benchmark test of all the different methods this sunday morning.

I used a vector with 1000000 items in and made 2 tests for each loop. One using the built in array functions push and one using regular array operations.

  • For loop, not push: 520 ms
  • For loop, push: 1027 ms
  • Foreach loop, not push: 1753 ms
  • Foreach loop, push: 2264 ms
  • While loop, not push: 2775 ms
  • While loop, not push: 3282 ms
  • Util loop, not push: 4059 ms
  • Util loop, push: 4570 ms

And here is a benchmark using 1000 items:

  • For loop, not push: 1 ms
  • For loop, push: 2 ms
  • Foreach loop, not push: 2 ms
  • Foreach loop, push: 3 ms
  • While loop, not push: 3 ms
  • While loop, not push: 4 ms
  • Util loop, not push: 4 ms
  • Util loop, push: 5 ms

Basically it's when you get over 10 000 items you start to see the real difference. So between 0 and 10 000 items it doesn't really matter which you use.

package
{
    public class Loops{
        public static function forLoop(vector:Vector.<Foo>, usePush:Boolean = false):Array{
            var result:Array = [];

            for(var i:int = 0; i < vector.length; i++){
                if(usePush){
                    result.push(vector[i]);
                }else{
                    result[result.length] = vector[i];
                }
            }

            return result;          
        }

        public static function foreachLoop(vector:Vector.<Foo>, usePush:Boolean):Array{
            var result:Array = [];

            for each(var key:String in vector){
                if(usePush){
                    result.push(vector[key]);
                }else{
                    result[result.length] = vector[key];
                }
            }

            return result;          
        }

        public static function whileLoop(vector:Vector.<Foo>, usePush:Boolean):Array{
            var result:Array = [];

            var i:int = 0;
            while(i < vector.length){
                if(usePush){
                    result.push(vector[i]);
                }else{
                    result[result.length] = vector[i];
                }
            }

            return result;                      
        }

        public static function arrayUtilLoop(vector:Vector.<Foo>, usePush:Boolean):Array{
            var result:Array = [];

            function arrayUtilForeach(element:*, index:int, array:Array):void{
                if(usePush){
                    array.push(element);
                }else{
                    array[result.length] = element;
                }
            }           

            vector.forEach(arrayUtilForeach);

            return result;          
        }
    }
}

I used the getTimer function to do the benchmark, so it might not be 100% accurate but there's so much difference between the different loops so I don't think it matters.

I hope someone found this useful.

18
ответ дан 29 November 2019 в 02:16
поделиться

вызов функции для каждого элемента вектора будет НАМНОГО медленнее, особенно в более длинном векторе. однако эти примеры, вероятно, все равнозначны, если только вы не имеете дело с довольно длинным вектором / массивом - разборчивость и простота использования, как правило, более важны, чем оптимизация.

При этом я думаю, что самый быстрый способ - использовать Цикл while с итератором сравнивается с 0.

var myArray:Array = new Array(myVector.length);
var i:int=myVector.length;
while (i--) {
    myArray[i] = myVector[i];
}

, к сожалению, вы не можете включить этот метод в метод для простоты повторного использования, потому что нет способа указать параметр метода Vector общего базового типа ....: (

0
ответ дан 29 November 2019 в 02:16
поделиться

Если у вас есть вектор строк, вы можете сделать:

myArray = myVec.join(",").split(",");

для быстрого и грязного преобразования массива.

-4
ответ дан 29 November 2019 в 02:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: