【发布时间】:2011-11-15 11:13:00
【问题描述】:
有没有比typeof更好的方法在JS中获取变量的类型?这样做时效果很好:
> typeof 1
"number"
> typeof "hello"
"string"
但是尝试了也没用:
> typeof [1,2]
"object"
>r = new RegExp(/./)
/./
> typeof r
"function"
我知道instanceof,但这需要你事先知道类型。
> [1,2] instanceof Array
true
> r instanceof RegExp
true
有没有更好的办法?
【问题讨论】:
-
仅供参考,Chrome 中的
typeof new RegExp(/./); // "function"问题似乎已在 Chrome 14 中得到修复。 -
警告:如果您正在缩小您的 JS 并且您正在使用诸如打字稿类之类的“自定义对象”,那么下面的一些答案最终会为您提供混淆的函数名称,例如
n而不是预期的原始名称。例如constructor.name可能会给你n而不是预期的全名
标签: javascript types typeof