Why is (new Date() == new Date()) false, but (Date() == Date()) is true? [duplicate]

若如初见. 提交于 2020-01-02 09:29:35

问题


I have been messing around with JSFiddle to solve this problem in FreeCodeCamp. When I use Date as a string (i.e., no "new"):

Case 1:

function isSameDay (dtFrom, dtTo) {
    return dtFrom == dtTo
  }

  let today = Date()
  let tomorrow = Date()

  console.log(today)
  console.log(tomorrow)
  console.log(isSameDay(today, tomorrow))

isSameDay returns true. However when I use Date as a constructor (with "new"):

Case 2:

function isSameDay (dtFrom, dtTo) {
    return dtFrom == dtTo
  }

  let today = new Date()
  let tomorrow = new Date()

  console.log(today)
  console.log(tomorrow)

  console.log(isSameDay(today, tomorrow))

isSameDay returns false. However(!), when I add the unary operator "+":

Case 3:

function isSameDay (dtFrom, dtTo) {
    return dtFrom == dtTo
  }

  let today = + new Date()
  let tomorrow = + new Date()

  console.log(today)
  console.log(tomorrow)

  console.log(isSameDay(today, tomorrow))

isSameDay returns true. I understand case 1 and case 3 returning true because they are just the same strings and the same millisecond values.

Why does case 2 return false?


回答1:


Using Date(), the JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object. MDN Reference.

typeof Date()    //"string"
Date() == Date() //true

Using instead a constructor as new Date(), each instance is unique (the two instances of the same constructor are still different to each-other), this is the reason why they are not equal when compared.

typeof new Date();        //"object"
new Date() === new Date() //false



回答2:


Simply put, Case 2 returns false because you are comparing two different object references (even if both objects contain the exact same properties).

Whereas in the other cases you are comparing the toString() value of the dates.

Please see Note 3 in the official documentation for the == Abstract Equality Algorithm

NOTE 3

The equality operator is not always transitive. For example, there might be two distinct String objects, each representing the same String value.

Each String object would be considered equal to the String value by the == operator, but the two String objects would not be equal to each other. For Example:

new String("a") == "a" //true

"a" == new String("a") //true 

but

new String("a") == new String("a") //false.


来源:https://stackoverflow.com/questions/41980177/why-is-new-date-new-date-false-but-date-date-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!