JavaScript 中 TypeError: toUTCString is not a function 错误
当对不是日期对象的值调用 toUTCString()
方法时,会发生“TypeError: toUTCString is not a function”错误。
要解决此错误,请在调用方法之前将值转换为日期,或确保仅对有效日期对象调用 toUTCString()
方法。
下面是一个产生上述错误的示例
const d = Date.now();
console.log(d); // 👉️ 1639....
// ⛔️ TypeError: toUTCString is not a function
const result = d.toUTCString();
我们调用了 Date.now()
函数,它返回一个整数,并试图对其调用 Date.toUTCString()
方法,这导致了错误。
仅对有效日期对象调用 toUTCString() 方法
要解决该错误,请确保仅对有效日期对象调用 toUTCString()
方法。
const d1 = new Date().toUTCString();
console.log(d1);
const d2 = new Date('Sept 24, 22 13:20:18').toUTCString();
console.log(d2); // 👉️ Sat, Sep 24 2022 10:20:18 GMT
我们可以通过将有效日期传递给 Date()
构造函数来获取日期对象。
请注意
,如果将无效日期传递给Date()
构造函数,将返回“Invalid date”。
const d1 = new Date('invalid').toUTCString();
console.log(d1); // 👉️ "Invalid Date"
我们可以使用 console.log
打印我们调用 toUTCString
方法的值,看看它是否是一个有效的 Date 对象。
在调用 toUTCString 之前检查该值是否为有效日期
我们可以通过以下方式有条件地检查该值是否为 Date
对象。
const d1 = new Date();
if (typeof d1 === 'object' && d1 !== null && 'toUTCString' in d1) {
const result = d1.toUTCString();
console.log(result); // 👉️ Thu, Dec 16 ...
}
我们的 if
条件使用逻辑与 &&
运算符,因此要运行 if 块,必须满足所有条件。
我们首先检查 d1 变量是否存储了具有对象类型的值,因为日期具有对象类型。
然后我们检查变量是否不等于 null。 不幸的是,如果使用 console.log(typeof null)
检查 null 的类型,我们将得到一个“对象”值,因此我们必须确保该值不为 null。
console.log(typeof null); // 👉️ object
我们检查的最后一件事是该对象包含
toUTCString
属性。
然后我们知道我们可以安全地对该对象调用 toUTCString
方法。
总结
当对不是日期对象的值调用 toUTCString()
方法时,会发生“TypeError: toUTCString is not a function”错误。
要解决此错误,需要在调用方法之前将值转换为日期,或确保仅对有效日期对象调用 toUTCString()
方法。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。