【问题标题】:Looping through array of dates to find out if any of them match a date given遍历日期数组以找出其中任何一个与给定日期匹配
【发布时间】:2019-10-01 08:01:46
【问题描述】:

我需要检查日期值是否等于我拥有的数组中的任何日期(包括时间值)。

由于某种原因,当我遍历这个数组时,angular 不会让我使用 getTime。如果我确实使用它,我会收到错误消息:element.start.getTime 不是函数。截至目前,由于我认为数组日期和 newEvent 的格式略有不同,因此即使存在等效日期,该函数也始终返回 false。

这里是有问题的函数:

 seeIfAppStartExists(appStart: Date) {
      let ret = false;
      this.eventsArray.forEach(element => {
       // tslint:disable-next-line: triple-equals
      if (element.start == appStart) {
            ret = true;
       }
   });

   return ret;

   }

【问题讨论】:

  • 听起来element.start 是一个字符串,而不是一个日期对象。根据minimal reproducible example 提供一个可运行的示例

标签: javascript arrays angular date


【解决方案1】:

如果调用getTime()函数时出现“.getTime is not a function”错误,则需要使用new关键字创建新的对象实例。

    let eventsArray = [{start : '2019-09-30T23:22:59.534Z'}, {start : '2019-11-30T23:22:59.534Z'}]
    function seeIfAppStartExists(appStart: Date) {
          let ret = false
          eventsArray.forEach(element => {
          let time = new Date(element.start)
          if (time.getTime() === appStart.getTime()) {
                ret = true;
           }
       });
       return ret;
    }

    console.log(seeIfAppStartExists(new Date('2019-09-30T23:22:59.534Z')))

【讨论】:

    【解决方案2】:

    您的实施存在一些问题。就像上面的答案所说,您可以使用 new Date(element.start) 来实际获取日期对象。然后,您可以在该对象上调用 getTime() 并使用它进行比较。但是您的逻辑的另一个问题是如何为每次迭代更改 ret 的值。本质上,您的代码只会告诉您 last 元素的开始时间是否与您的appStart 匹配。因为那是在最后设置ret 的值。所有其他值都将被忽略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多