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
How to test if a variable is a Moment.js object?
提问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 time
input). An onChange
function runs through each input when the user changes a value.
我的应用程序有一个 HTML 表单,其中一些输入从后端填充,其他输入由用户time
输入(在输入中)。的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.
从后端填充的输入被转换为moment
对象,用户输入的日期只是字符串。这意味着该onChange
函数会遇到一些moment
对象和一些字符串。我需要知道哪些输入是moment
对象,哪些不是。
What's the recommended method for testing if a variable is a moment
object?
测试变量是否为moment
对象的推荐方法是什么?
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
属性,但我想知道是否有另一种方法来测试变量是否是moment
对象。
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.
我尝试过的另一个选择是moment
无论如何调用变量。这会将string
变量转换为moment
对象,并且似乎不会影响现有moment
对象。
采纳答案by Jared Smith
Moment has an isMoment
methodfor 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
属性。
回答by Niels Heisterkamp
You can check if it is an instanceof
moment:
您可以检查是否是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()