猿问

有一个时间数组,时次不连续,怎样补全比较好?

一个时间数组,比如:

var times = [    '2018-5-15 00:00:00','2018-5-15 01:00:00','2018-5-15 02:00:00','2018-5-15 08:00:00','2018-5-16 03:00:00'
]

像这样,补全之间缺失的时次,怎样实现较好?


慕斯王
浏览 509回答 3
3回答

呼啦一阵风

这看起来,不是一个补全的题,是按照间隔1小时生成下标0和下标length-1的时间间隔数组的问题。let times = [&nbsp; &nbsp; '2018-5-15 00:00:00', '2018-5-15 01:00:00', '2018-5-15 02:00:00', '2018-5-15 08:00:00', '2018-5-16 03:00:00']let oneHour = 60 * 60 * 1000;let now = new Date(times[0]);let max = new Date(times[times.length - 1]);let result = [];while (!(max < now)) {&nbsp; &nbsp; result.push(now)&nbsp; &nbsp; now = new Date(now.getTime() + oneHour);}console.log(result)还是用moment.js比较方便。

RISEBY

你的需求是补全两个时间段之间缺失的小时时间对吧,看到你的数组是排好序的,很简单呀,你可以取出数组首跟尾,然后转成时间戳,接着用个for循环,只要小于尾部时间戳的,就一直加一个小时,存入一个新数组,最后将新数组装回字符串,完成。

慕妹3242003

&nbsp;var times = [&nbsp; &nbsp; &nbsp; '2018-5-15 00:00:00','2018-5-15 01:00:00','2018-5-15 02:00:00','2018-5-15 08:00:00','2018-5-16 03:00:00'];&nbsp; var oneHour = 60*60*1000;&nbsp; var index = 0;&nbsp; while(index<times.length-1){&nbsp; &nbsp; &nbsp; var next = new Date(new Date(times[index]).getTime()+oneHour);&nbsp; &nbsp; &nbsp; if(next<new Date(times[index+1])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; times.splice(index+1,0,next);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; index++;&nbsp; }&nbsp; alert(times);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答