type of Date object

时间:2016-04-25 09:07:56

标签: javascript date

I just read this article on W3Schools about type conversion in JS. There stands:

There are 3 types of objects:

  • Object
  • Date
  • Array

This confused me because to my knowledge there isn't any difference between Date objects and any other object (typeof (new Date()) returns "object"). First I thought that it's special because it contains native code, but there are dozens of functions with native code.

Is this article wrong? Or could anybody tell my why the Date object is so extraordinary that it's considered a separate type of object?

3 个答案:

答案 0 :(得分:13)

Lemme tell you a basic thing. The articles in W3Schools are definitely outdated so you must not rely on it. Yes, when you give this in console:

typeof (new Date())

The above code returns object because the JavaScript has only a few primitive types:

You can check if it is a date object or not using:

(new Date()) instanceof Date

The above code will return true. This is the right way of checking if the particular variable is an instance of a particular type.

答案 1 :(得分:1)

您可以通过验证对象是否具有特定于相关对象类型的方法来检查对象是否为特定类型的实例:

if (myobject.hasOwnProperty("getUTCMilliseconds")) {
    // myobject is a Date...

相同的技术可以帮助您在Javascript中识别数组:
检查

typeof(myobject)  
如果"object"确实是一个数组,

产生"array",而不是myobject,所以我使用

if (myobject.hasOwnProperty("slice")) {
    // we are dealing with an array here ...

答案 2 :(得分:0)

您可以使用(已建议)

(new Date) instanceof Date

(new Date).constructor === Date

老实说,我更喜欢使用constructor选项,但这只是一个首选项。