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

date.GetMonth()不是函数

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

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

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

谢谢

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


当前回答

使用try/catch的方法

函数getFormattedDate(date=new date()){尝试{date.toISOString();}捕获(e){date=新日期();}返回日期;}console.log(getFormattedDate());console.log(getFormattedDate('AAAA'));console.log(getFormattedDate(新日期('AAAA')));console.log(getFormattedDate(新日期(2018,2,10));

其他回答

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

为了检查该值是否是标准JS日期对象的有效类型,可以使用此谓词:

function isValidDate(date) {
  return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}

date检查参数是否不是错误值(undefined、null、0、“”等)Object.prototype.toString.call(date)返回给定对象类型的本机字符串表示形式-在我们的例子中是“[Object date]”。因为date.toString()重写了它的父方法,所以我们需要直接调用或应用Object.prototype中的方法。。绕过具有相同构造函数名称的用户定义对象类型(例如:“Date”)与instanceof或Date.prototype.isPrototypeOf不同,可以跨不同的JS上下文(例如iframes)工作。!isNaN(date)最后检查该值是否不是无效日期。

使用以下方法,您甚至可以将日期no检查为“无效日期”

if(!!date.getDate()){
    console.log('date is valid')
}

你就不能用

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

使用try/catch的方法

函数getFormattedDate(date=new date()){尝试{date.toISOString();}捕获(e){date=新日期();}返回日期;}console.log(getFormattedDate());console.log(getFormattedDate('AAAA'));console.log(getFormattedDate(新日期('AAAA')));console.log(getFormattedDate(新日期(2018,2,10));