我有一个包含
等对象的数组var array = [{x:'Thu Jul 27 2017 01:00:00 GMT+0200 (Central European Daylight Time)',y:1},
{x:'Thu Jul 27 2017 01:10:00 GMT+0200 (Central European Daylight Time)',y:5},
{x:'Thu Jul 27 2017 01:15:00 GMT+0200 (Central European Daylight Time)',y:3},
...
{x:'Thu Jul 27 2017 23:55:00 GMT+0200 (Central European Daylight Time)',y:8},
];
我需要用5分钟检查每个间隔时间。假设我的开始和结束时间是
var start = 'Thu Jul 27 2017 01:00:00 GMT+0200 (Central European Daylight Time)';
var end = 'Thu Jul 27 2017 23:55:00 GMT+0200 (Central European Daylight Time)';
如果缺少任何间隔数据,我需要以给定的时间间隔推送该对象作为关键字' x'并且' y'为0.表示我的输出必须如下所示 -
var output= [{x:'Thu Jul 27 2017 01:00:00 GMT+0200 (Central European Daylight Time)',y:1},
{x:'Thu Jul 27 2017 01:05:00 GMT+0200 (Central European Daylight Time)',y:0},
{x:'Thu Jul 27 2017 01:10:00 GMT+0200 (Central European Daylight Time)',y:5},
{x:'Thu Jul 27 2017 01:15:00 GMT+0200 (Central European Daylight Time)',y:3},
...
{x:'Thu Jul 27 2017 23:55:00 GMT+0200 (Central European Daylight Time)',y:8},
];
缺少对象{x:' Thu Jul 27 2017 01:05:00 GMT + 0200(中欧夏令时)',y:0}已被添加。 我尝试了什么。
var start = 'Thu Jul 27 2017 01:00:00 GMT+0200 (Central European Daylight Time)';
var end = 'Thu Jul 27 2017 23:55:00 GMT+0200 (Central European Daylight Time)';
var interval = 300000;
//loop through every 5 minute interval
for(var dt = start;dt<end;dt = new Date(dt.getTime()+ interval)){
if( !lookup( dt , array ) ) {
array .push({
x: dt,
y: 0
});
}
}
console.log("Unsorted output is" + array);// result
function lookup( name,arr ) {
for(var i = 0, len = arr.length; i < len; i++) {
if( arr[ i ].key === name )
return true;
}
return false;
}
就我的逻辑而言,我看到一切都还可以,但我看不到丢失的间隔。谁能帮助我,我做错了什么。 提前谢谢。
答案 0 :(得分:0)
为什么不尝试将对象转换为毫秒并进行比较...
代码片段应该更简单一些,并为您提供我所谈论的内容的要点。
在这个例子中,我创建了一个数组,它保存每个日期对象的millisec值。循环实际对象并使用getTime()
方法将其动态转换为毫秒,虽然未经测试......这可能比一次推送转换后的整数要慢。
这给您留下的唯一挑战是订购以及您是否需要订购日期......使用此方法,它只是将新值推送到最后的对象中。
注意代码未经测试 - 只需提供一个通用的IDEA
//create an array in tandem with your objects array that holds the millisec value
var millisecArray = [];
for(var i = 0; i < array.length; i++) { //loop through the existing date object array
millisecArray.push(array[i]['x'].getTime()); //and push its millisec value into the new array
}
var start = startObj.getTime(); //gets the time in millisecs
var end = endObj.getTime(); //gets the time in millisecs
var interval = 300000;
var newDateObj = new Date();
//loop through every 5 minute interval
for(var current = start; current < end; current = current + interval;){ //keep looping until current is 5 minutes smaller than end
if( !lookup( current , millisecArray ) ) {
array.push({
x: newDateObj.setTime(current),
y: 0
});
millisecArray.push(current);
}
}
function lookup( name,arr ) {
for(var j = 0; i < arr.length; j++) {
if( arr[ j ] === name )
return true;
}
return false;
}
&#13;