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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36457220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:05:47  来源:igfitidea点击:

How to test if a variable is a Moment.js object?

javascriptmomentjs

提问by Brett DeWoody

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

我的应用程序有一个 HTML 表单,其中一些输入从后端填充,其他输入由用户time输入(在输入中)。的onChange功能,当用户改变一个值贯穿每个输入。

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

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

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

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

I've noticed momentobjects have a _isAMomentObjectproperty but I'm wondering if there's another way to test if a variable is a momentobject.

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

Another option I've tried is calling momenton the variable regardless. This converts the stringvariables to momentobjects and doesn't seem to effect existing momentobjects.

我尝试过的另一个选择是moment无论如何调用变量。这会将string变量转换为moment对象,并且似乎不会影响现有moment对象。

采纳答案by Jared Smith

Moment has an isMomentmethodfor 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 instanceofand then failing that (for instance in certain subclassing or cross-realm situations) it will test for the _isAMomentObjectproperty.

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

回答by Niels Heisterkamp

You can check if it is an instanceofmoment:

您可以检查是否是instanceof片刻:

moment() instanceof moment; // true

回答by Fabien Sartori

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()
  • 时刻(属性)。isValid()