【问题标题】:Why do this dates not match?为什么这个日期不匹配?
【发布时间】:2023-01-08 22:36:54
【问题描述】:

我有这段代码适用于日期:

let startDate = new Date(toolOrder.jsAppStartDate.getTime()); // clone date
startDate.setDate(startDate.getDate() - Math.floor((days - 1) / 2)); // sub some days
console.log(toolOrder.jsAppStartDate); // Output: Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
console.log(toolOrder.jsAppStartDate.getTime()); // Output: 1695247200000
console.log("--------------");
for (let index = 0; index < days; index++)
{
    console.log(startDate);
    console.log(startDate.getTime());
    // ... some drawing code here ...
    startDate.setDate(startDate.getDate() + 1); // add one day
    if(startDate === toolOrder.jsAppStartDate) // check if start date reached
    {
        console.log("Dates match");
        startDate = new Date(toolOrder.jsAppEndDate.getTime());
    }
}

循环前的日志输出为:

Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
---------------

循环的输出是:

Date Mon Sep 18 2023 00:00:00 GMT+0200 (Central European Summer Time)
1694988000000 
Date Tue Sep 19 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695074400000
Date Wed Sep 20 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695160800000
Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
Date Fri Sep 22 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695333600000

因此,即使日期在循环 3 中匹配,if 条件也不成立。它在我使用时有效

if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())

但我认为它也应该在没有的情况下工作?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    ===比较身份所以:

    startDate === toolOrder.jsAppStartDate
    

    表示:与startDate相同目的[在内存中] 为 toolOrder.jsAppStartDate 但事实并非如此,因为 toolOrder.jsAppStartDate 是一个不同的对象而不是名称 startDate 引用的对象。

    mdn 是关于严格相等运算符的:

    如果两个操作数是对象, 返回真的只有当他们提到同一个对象.

    (强调我的)

    if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())
    

    之所以可行,是因为您现在比较的是字符串而不是对象。

    两个操作数都是字符串的规则是:

    否则,比较两个操作数的值:

    字符串必须具有相同顺序的相同字符。

    mdn(强调我的)

    【讨论】:

      【解决方案2】:

      当您使用 === 运算符时,您正在相互比较 Date 实例。但是,它们不是同一个实例。每个new Date 都会创建一个唯一的新实例(除非类构造函数有意返回先前创建的实例 [有关更多信息:singleton pattern])。

      当您比较每个实例的 getTime() 结果时,您正在比较 2 个原始值(在本例中为数字)。原始值不是类实例;所以 ===== 一样使用原语。

      【讨论】:

        猜你喜欢
        • 2020-12-20
        • 2012-01-04
        • 2012-09-17
        • 1970-01-01
        • 2017-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多