【问题标题】:2 values in 2 objects that are equal but still calculate as not equal when compared2 个对象中的 2 个值相等,但在比较时仍计算为不相等
【发布时间】:2020-07-13 07:23:24
【问题描述】:

我有 2 个对象数组 对象的结构是完全一样的,有一个key,一个timestamp,还有一些其他的东西

arr1 = [{key: 2, timestamp:2020-07-07T02:00:00.000Z},other stuff:....}...]
arr2 = [{key: 7, timestamp:2020-07-07T02:00:00.000Z},other stuff:....}...]

arr1 按小时跟踪事物,因此每个时间戳都是每小时一次 arr2 每 15 分钟跟踪一次,因此其中有类似 2020-07-07T02:45:00.000Z 的时间戳

我想要做的是找到两个数组中的时间戳匹配 我遍历 1 个数组,然后传入时间戳以在另一个数组中搜索它

问题是它没有找到匹配的值,即使我知道它在那里

arr1.map(function (e) {
        console.log(e.timestamp, arr2[3].timestamp, e.timestamp == arr2[3].timestamp )
      }); 

所以上面的代码遍历 arr1 中的所有时间戳值,然后控制台记录它们,加上我知道 arr1 中的 arr2 中的特定值,然后我在控制台记录比较

控制台日志打印的内容如下

2020-07-07T02:00:00.000Z 2020-07-07T02:00:00.000Z false

false 应该是 true 不应该吗????

注意:我尝试过使用 =====,但都产生了 false

【问题讨论】:

    标签: javascript arrays dictionary


    【解决方案1】:

    你不能这样比较时间戳,因为时间戳是对象。

    
    new Date('2020-07-07T02:00:00.000Z') == new Date('2020-07-07T02:00:00.000Z')
    
    // false
    

    让我们试试 (e.timestamp - arr2[3].timestamp) == 0)

    arr1.map(function (e) {
        console.log(e.timestamp, arr2[3].timestamp, (e.timestamp - arr2[3].timestamp) == 0);
    }); 
    

    【讨论】:

      猜你喜欢
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多