JavaScript 中 TypeError: date.getDay is not a function 错误
当对不是日期对象的值调用 getDay()
方法时,会发生“TypeError: date.getDay is not a function”错误。
要解决此错误,需要在调用方法之前将值转换为日期,或确保仅对有效日期对象调用 getDay()
方法。
下面是产生上述错误的一个示例
const date = Date.now();
console.log(date); // 👉️ 1639...
// ⛔️ TypeError: date.getDay is not a function
const result = date.getDay();
我们调用了 Date.now()
函数,它返回一个整数,并试图在其上调用 Date.getDay()
方法,所以错误发生了。
只在有效的日期对象上调用 getDay() 方法
要解决该错误,请确保仅对有效日期对象调用 getDay()
方法。
const d1 = new Date().getDay();
console.log(d1); // 👉️ 4
const d2 = new Date('Sept 24, 22 13:20:18').getDay();
console.log(d2); // 👉️ 6
我们可以通过将有效日期传递给 Date()
构造函数来获取日期对象。
在无效日期调用方法返回 NaN
请注意
,如果将无效日期传递给Date()
构造函数,将返回 NaN(不是数字)值。
const d1 = new Date('invalid').getDay();
console.log(d1); // 👉️ NaN
我们可以使用 console.log
打印正在调用 getDay
方法的值并查看它是否是有效的 Date 对象。
在调用 getDay 之前检查该值是否为 Date 对象
我们可以通过以下方式有条件地检查该值是否为 Date 对象。
const d1 = new Date();
if (typeof d1 === 'object' && d1 !== null && 'getDay' in d1) {
const result = d1.getDay();
console.log(result); // 👉️ 4
}
我们的 if
条件使用逻辑与 &&
运算符,因此要运行 if 块,必须满足所有条件。
我们首先检查 d1 变量是否存储了具有对象类型的值,因为日期具有对象类型。
然后我们检查变量是否不等于 null。 不幸的是,如果我们检查 null 的类型 - console.log(typeof null)
,我们将得到一个“object”值,因此我们必须确保该值不为 null。
console.log(typeof null); // 👉️ object
我们检查的最后一件事是该对象包含
getDay
属性。
然后我们知道我们可以安全地对该对象调用 getDay()
方法。
总结
当对不是日期对象的值调用 getDay()
方法时,会发生“TypeError: date.getDay is not a function”错误。
要解决此错误,请在调用方法之前将值转换为日期,或确保仅对有效日期对象调用 getDay()
方法。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。