过滤数组中的数据

时间:2010-04-22 18:33:29

标签: javascript flex flash actionscript-3

我有一个有30个日期对象的数组。日期对象在数组中从最小日期值到最大日期值建立索引。我想做的是从数组中只检索7个日期。在7中,第一个应该是minDate,最后一个应该是maxDate,中间有5个日期。 7个数字应该从minDate到maxDate均匀增加。我怎么做到这一点?希望我很清楚。

谢谢, Tonih

1 个答案:

答案 0 :(得分:1)

如果您尝试按日期均匀分布,那么请确保所有对象都在日期类中,然后执行数组[29] .getTime() - array [0] .getTime()/ 7作为平均步骤,然后使用comparerason函数执行类似array.forEach()的操作,尝试最接近每一步。

- 编辑 -

尝试类似:

//dateArray is array of dates

var targetTime:Number;
var filteredarray:Array = new Array();
var step = dateArray[29].getTime()-dateArray[0].getTime() /7

var smallestdist:Number;
var currentIndex:int;

filteredarray.push(dateArray[0]); //Add the first entry
targetTime = dateArray[29].getTime(); //set the lowest point
for(var i=1; i<7; i++){ //loop 6 more times
    smallestdist = Number.POSITIVE_INFINITY; //set a large smalldist
    currentIndex = 0; //Set a small index
    targetTime += step; //increment the target time
    dateArray.forEach(testDate); //loop through the array and test with testDate function
    filteredarray[i] = dateArray[currentIndex] //Add the result to the dateArray
}

function testDate(item:Date, index:int, array:Array){
    //Check the absolute value against current stored distance
    if(Math.abs(item.getTime() - targetTime) < smallestdist){ 
        //if less then set this as new target
        smallestdist = Math.abs(item.getTime() - targetTime);
        currentIndex = index;
    }
}

当然这是处理假设的日期扩展,如果所有dateArray都聚集在一起,可以优化,可以将相同的日期添加到几个不同的点,但是看看你可以用它做什么

我已经测试了这段代码,但它应该可以开箱即用。如果您遇到问题,请查看这些内容:

Array::forEach()

Date::getTime()