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

时间:2022-04-28 21:30:33

My application has an HTML form with some inputs populated from the backend and other inputs being entered by the user (in a time input). An onChange function runs through each input when the user changes a value.

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

The inputs populated from the backend are converted to moment objects, the user-entered dates are mere strings. This means the onChange function encounters some moment objects, and some strings. I need to know which inputs are moment objects and which aren't.

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

What's the recommended method for testing if a variable is a moment object?

如果变量是一个矩形对象,测试的推荐方法是什么?

I've noticed moment objects have a _isAMomentObject property but I'm wondering if there's another way to test if a variable is a moment object.

我注意到moment对象有一个_isAMomentObject属性,但我想知道是否有另一种方法来测试变量是否是一个时刻对象。

Another option I've tried is calling moment on the variable regardless. This converts the string variables to moment objects and doesn't seem to effect existing moment objects.

我尝试过的另一个选择是无论如何都要调用变量。这会将字符串变量转换为时刻对象,但似乎不会影响现有的时刻对象。

2 个解决方案

#1


48  

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.

为了这个目的,Moment有一个isMoment方法。除非您知道要查找什么,否则在文档中查找并不是特别容易。

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

它首先检查instanceof然后失败(例如在某些子类或跨领域情况下)它将测试_isAMomentObject属性。

#2


21  

You can check if it is an instanceof moment:

您可以检查它是否是瞬间的实例:

moment() instanceof moment; // true

#1


48  

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.

为了这个目的,Moment有一个isMoment方法。除非您知道要查找什么,否则在文档中查找并不是特别容易。

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

它首先检查instanceof然后失败(例如在某些子类或跨领域情况下)它将测试_isAMomentObject属性。

#2


21  

You can check if it is an instanceof moment:

您可以检查它是否是瞬间的实例:

moment() instanceof moment; // true