在JavaScript中查找变量类型 [英] Finding Variable Type in JavaScript
问题描述
在Java中,您可以对变量使用 instanceOf
或 getClass()
来查找其类型。
In Java, you can use instanceOf
or getClass()
on a variable to find out its type.
如何在JavaScript中找出不是强类型的变量类型?
How do I find out a variable's type in JavaScript which isn't strongly-typed?
例如,我怎么知道栏
是布尔
还是数字
,或字符串
?
For example, how do I know if the bar
is a Boolean
or a Number
, or a String
?
function foo(bar) {
// what do I do here?
}
推荐答案
使用 typeof
:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
所以你可以这样做:
if(typeof bar === 'number') {
//whatever
}
小心但是如果用它们的对象包装器定义这些原语(你永远不应该这样做,尽可能使用文字):
Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):
> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"
数组的类型仍然是物体
。在这里,你真的需要 instanceof
运营商。
The type of an array is still object
. Here you really need the instanceof
operator.
更新:
另一种有趣的方式是检查 Object.prototype.toString
:
Another interesting way is to examine the output of Object.prototype.toString
:
> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"
With您不必区分原始值和对象。
With that you would not have to distinguish between primitive values and objects.
这篇关于在JavaScript中查找变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!