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

date.GetMonth()不是函数

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

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

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

谢谢

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


当前回答

我一直在使用一种更简单的方法,但不确定这是否仅在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无效,因为它们没有构造函数。

其他回答

函数是getMonth(),而不是getMonth(。

无论如何,您可以通过执行此操作来检查对象是否具有getMonth属性。这并不一定意味着对象是Date,而是任何具有getMonth属性的对象。

if (date.getMonth) {
    var month = date.getMonth();
}

也可以使用简短形式

function getClass(obj) {
  return {}.toString.call(obj).slice(8, -1);
}
alert( getClass(new Date) ); //Date

或者类似的东西:

(toString.call(date)) == 'Date'

我们也可以通过以下代码验证它

var a = new Date();
a.constructor === Date
/*
true
*/

您可以使用以下方法代替所有的变通方法:

dateVariable = new Date(date);
if (dateVariable == 'Invalid Date') console.log('Invalid Date!');

我发现这个黑客更好!

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

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