2016-06-30 50 views
0

如下所示,控制檯中未打開的對象的x(日期)屬性是正確的,直到我打開它們並顯示實際數據爲:日期數據在控制檯中正確顯示,但未正確保存在對象中

星期一2016年6月6日十六時19分28秒GMT + 1000(AEST)

這究竟是爲什麼?

enter image description here


我的代碼基本上得到可變日期訂單的數組。它使用getDataInRange將它們分組在一致的時間範圍內。然後使用getAverageInRange將這些時間範圍縮小爲平均值。

  1. getDataInRange(對象:陣列,startRange:整數,endRange:整數)
  2. getAverageInRange(objectsWithinInterval:陣列,currentTimeMiliseconds:整數,timePositionToSet:整數)
  3. normaliseData(對象:陣列,millisecondInterval:整數)

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; 
} 

回答

0

分配平均可變的副本,而不是一個指派變量本身爲我解決了這個問題。

更改:

prevAverage = average; 

要:

prevAverage = duplicateObject(average); 

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