我在网页上有一个烦人的bug:

date.GetMonth()不是函数

所以,我想我做错了什么。变量date不是date类型的对象。如何在Javascript中检查数据类型?我试图添加一个if(日期),但不起作用。

function getFormatedDate(date) {
    if (date) {
       var month = date.GetMonth();
    }
}

所以,如果我想编写防御性代码并防止日期(不是一个)被格式化,我该怎么做?

谢谢

UPDATE:我不想检查日期的格式,但我想确保传递给getFormatedDate()方法的参数是date类型。


当前回答

箭头函数

const isValidDate = (value: any) => value instanceof Date && !isNaN(value);

功能:

function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}

其他回答

如果该函数为Date,则返回true,否则返回false:

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
} 

您可以使用以下代码:

(myvar instanceof Date) // returns true or false

作为通过

typeof date.getMonth === 'function'

您可以使用instanceof运算符,即,对于无效日期,它也将返回true,例如,new Date('random_string')也是Date的实例

date instanceof Date

如果对象跨越帧边界传递,则此操作将失败。

解决方法是通过

Object.prototype.toString.call(date) === '[object Date]'

箭头函数

const isValidDate = (value: any) => value instanceof Date && !isNaN(value);

功能:

function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}

我一直在使用一种更简单的方法,但不确定这是否仅在ES6中可用。

let a = {name: "a", age: 1, date: new Date("1/2/2017"), arr: [], obj: {} };
console.log(a.name.constructor.name); // "String"
console.log(a.age.constructor.name);  // "Number"
console.log(a.date.constructor.name); // "Date"
console.log(a.arr.constructor.name);  // "Array"
console.log(a.obj.constructor.name);  // "Object"

然而,这对null或undefined无效,因为它们没有构造函数。