为什么(new Date()== new Date())为假,而(Date()== Date())为真? [英] Why is (new Date() == new Date()) false, but (Date() == Date()) is true?

查看:189
本文介绍了为什么(new Date()== new Date())为假,而(Date()== Date())为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在与JSFiddle纠缠在一起,以解决FreeCodeCamp中的问题。当我使用Date作为字符串(即没有 new)时:

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

情况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返回 true 。但是,当我使用Date作为构造函数(带有 new)时:

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

情况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返回 false 。但是(!),当我添加一元运算符 +时:

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

情况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返回 true 。我了解情况1和情况3返回true,因为它们只是相同的字符串和相同的毫秒值。

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

为什么情况2返回 false

推荐答案

使用 Date(),JavaScript Date对象只能可以通过调用JavaScript Date作为构造函数实例化:作为常规函数调用(即不使用new运算符)将返回字符串,而不是Date对象。 MDN参考

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

使用构造函数作为 new Date(),每个实例都是唯一的(两个实例同一构造函数的实例彼此之间仍然是不同的),这就是为什么它们在比较时不相等的原因。

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

这篇关于为什么(new Date()== new Date())为假,而(Date()== Date())为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆