在 JavaScript 中查找变量类型
2022-08-30 01:43:04
在 Java 中,您可以使用 或 在变量上找出其类型。instanceOf
getClass()
如何在JavaScript中找出一个不是强类型的变量类型?
例如,我如何知道 是 a 还是 a ,还是 a ?bar
Boolean
Number
String
function foo(bar) {
// what do I do here?
}
在 Java 中,您可以使用 或 在变量上找出其类型。instanceOf
getClass()
如何在JavaScript中找出一个不是强类型的变量类型?
例如,我如何知道 是 a 还是 a ,还是 a ?bar
Boolean
Number
String
function foo(bar) {
// what do I do here?
}
使用类型
:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
所以你可以做:
if(typeof bar === 'number') {
//whatever
}
但是,如果您使用对象包装器定义这些基元,请小心(您永远不应该这样做,请尽可能使用文本):
> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"
数组的类型仍然是 。在这里,您确实需要实例运算符
。object
更新:
另一个有趣的方法是检查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]"
这样,您就不必区分基元值和对象。
typeof 仅适用于返回“基元”类型,如数字、布尔值、对象、字符串和符号。您还可以 使用 来测试对象是否属于特定类型。instanceof
function MyObj(prop) {
this.prop = prop;
}
var obj = new MyObj(10);
console.log(obj instanceof MyObj && obj instanceof Object); // outputs true