有没有比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
有没有更好的办法?
最佳答案
Angus Croll 最近写了一篇关于此的有趣博客文章 -
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
他分析了各种方法的优缺点,然后定义了一个新方法 'toType' -
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
关于javascript - 获取 Javascript 变量类型的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7390426/