如何测试变量是否是 Moment.js 对象?

我的应用程序有一个 HTML 表单,其中一些输入由后端填充,其他输入由用户输入(在 time输入中)。当用户更改值时,onChange函数将遍历每个输入。

后端填充的输入被转换成 moment对象,用户输入的日期只是字符串。这意味着 onChange函数遇到一些 moment对象和一些字符串。我需要知道哪些输入是 moment对象,哪些不是。

测试变量是否是 moment对象的推荐方法是什么?

我已经注意到 moment对象具有 _isAMomentObject属性,但是我想知道是否还有其他方法来测试变量是否是 moment对象。

我尝试的另一个选项是对变量调用 moment。这会将 string变量转换为 moment对象,而且似乎不会影响现有的 moment对象。

53518 次浏览

You can check if it is an instanceof moment:

moment() instanceof moment; // true

Moment has an isMoment method for just such a purpose. It is not particularly easy to find in the docs unless you know what to look for.

It first checks instanceof and then failing that (for instance in certain subclassing or cross-realm situations) it will test for the _isAMomentObject property.

moment() instanceof moment;

will always be true, because if you have

  • moment(undefined) instanceof moment
  • moment("hello") instanceof moment

you are always creating a moment object. So the only way is to check like this

  • moment(property).isValid()

Pretty similar to the answer by @Fabien, I'm checking the object if the isValid function is available.

const checkMoment = (date) => {
if(!date.isValid){ // check if it's not a moment object
// do something if it's not moment object
console.log('this is not a moment object');
}
else {
// do something if it's a moment object
console.log('this is a moment object');
}
   

}