日期数据在控制台中正确显示,但未正确保存在对象中

时间:2016-06-30 10:06:07

标签: javascript google-chrome

如下所示,控制台中未打开对象的x(日期)属性是正确的,直到我打开它们并显示真实数据:

  

2016年6月6日星期一16:19:28 GMT + 1000(AEST)

为什么会这样?

enter image description here

我的代码基本上获得了一组具有可变日期的订单。它使用getDataInRange将它们分组在一致的时间范围内。然后使用getAverageInRange将这些时间范围缩小到平均值。

  1. getDataInRange(objects:array,startRange:integer,endRange:integer)
  2. getAverageInRange(objectsWithinInterval:array,currentTimeMiliseconds:integer,timePositionToSet:integer)
  3. normaliseData(objects:array,millisecondInterval:integer)
  4. var getDataInRange = function (data, start, end) {
        return data.filter(function (eachThing) {
            var currentDate = new Date(eachThing.created_at).getTime();
            return currentDate >= start && currentDate <= end;
        })
    }
    
    var getAverageInRange = function (range, time, interval) {
    
        // if there is no data
        if (range.length <= 0) {
            return null;
        }
    
        var avgPrice = range.map(function (order) {
            return parseFloat(order.price)
        }).reduce(function (current, next) {
            return current + next;
        }, 0);
    
        priceTime = {
            x: new Date(interval),
            y: avgPrice,
        }
        return priceTime
    }
    
    var normaliseData = function (data, interval) {
    
        var results = [];
    
        var start =  new Date(data[0].created_at).getTime();
        var end = new Date(data[data.length - 1].created_at).getTime()
        var range = end - start;
        var startRange;
        var prevAverage = null;
    
    
        // loop
        // this will loop through each interval
        for ( let i = start; i < end; i += interval) {
    
            var currentDatePoint = i - (interval/2)
            // GET START RANGE
    
            if (i >= interval * 2) {
                startRange = i - interval;
            } else {
                startRange = 0;
            }
    
            var range = getDataInRange(data, startRange, i);
    
            var average = getAverageInRange(range, i, currentDatePoint);
    
    
            if ( average === null ){
                prevAverage.x = new Date(currentDatePoint);
                average = prevAverage;
            }
    
            console.log(average);
            results.push(average);
            prevAverage = average;
        }
    
        return results;
    }
    

1 个答案:

答案 0 :(得分:0)

分配平均变量的副本而不是分配变量本身为我解决了这个问题。

已更改:

prevAverage = average;

致:

prevAverage = duplicateObject(average);

var duplicateObject = (object) => {
        var obj = {}
        for (var key in object) {
            obj[key] = object[key]
        }
        return obj;
    }