循环数组里的相邻项,数据怎么相减

现在有个数组:现在要算出第一条数据和第二条数据的时间差,第二条和第三条的时间差,以此类推,后面还有很多条数据,不固定

 historyList: [{
        id:1,
        date:'2019-01-18 14:08'
      },{
        id:2,
        date:'2019-01-19 14:08'
      },{
        id:3,
        date:'2019-01-20 14:08'
      }]

我写到这里没有思路了:不知道该怎么取出相邻两项来相减?

if (ctx.historyList.length > 1) {
            ctx.historyList.forEach((item, index) => {
              console.log(ctx.historyList[index].date)
            })
          }
阅读 4.3k
4 个回答
var historyList = [{
        id:1,
        date:'2019-01-18 14:08'
      },{
        id:2,
        date:'2019-01-19 14:08'
      },{
        id:3,
        date:'2019-01-20 14:08'
      }];
for(let i = 0; i < historyList.length - 1; i++) {
    console.log(new Date(historyList[i + 1].date).getTime() - new Date(historyList[i].date).getTime());
}
let result = [];
historyList.reduce((pre, curr) => {
    if (pre) {
        result.push(new Date(curr.date) - new Date(pre));
    }
    return curr.date;
}, 0);

result就是毫秒数插值 如果需要其他处理就在push之前做。。比如转换成别的格式啥的

unix时间戳 了解下。

如有帮助,请采纳
clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题