首页 > 解决方案 > 内部循环条件与nodejs不匹配

问题描述

内部循环条件未得到满足请指导如何得到这个以及是什么原因造成的?

var inputDate = '2020-04-11';
var result = []
for (var l = 0; l < reports.length; l++) {
  let myReport = {}
  myReport = await req.models.myReports.findAll({
    where: {
      id: reports[l].myReportId
    }
  })


  // I am getting values in myReport[0].lastDate like : '2019-04-10', '2020-01-01', '2024-05-12'
  // As i can see last last value is greater then inputDate it should not be went through if condition that mean result should stay blank but it does allow don't know why
  if ((inputDate > myReport[0].lastDate)) {
    result.push(myReport[0].name)
  }

}

标签: javascriptnode.js

解决方案


由于 inputDate 变量是一个字符串,并且您可能将一个字符串与另一个字符串进行比较,这是一个字符串比较,而不是日期,我会首先将您的字符串解析为日期,然后比较它们。

  var inputDate = Date.parse('2020-04-11');
    var result = []
    for (var l = 0; l < reports.length; l++) {
      let myReport = {}
      myReport = await req.models.myReports.findAll({
        where: {
          id: reports[l].myReportId
        }
      })
    
    
      // I am getting values in myReport[0].lastDate like : '2019-04-10', '2020-01-01', '2024-05-12'
      // As i can see last last value is greater then inputDate it should not be went through if condition that mean result should stay blank but it does allow don't know why
      if ((inputDate > Date.parse(myReport[0].lastDate))) {
        result.push(myReport[0].name)
      }
    
    }

推荐阅读