获取Javascript变量类型的更好方法是什么? [英] Better way to get type of a Javascript variable?
本文介绍了获取Javascript变量类型的更好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更好的方法来获取JS中的变量类型而不是 typeof
?它可以正常工作:
Is there a better way to get the type of a variable in JS than typeof
? It works fine when you do:
> typeof 1
"number"
> typeof "hello"
"string"
但是当你尝试时它没用了:
But it's useless when you try:
> typeof [1,2]
"object"
>r = new RegExp(/./)
/./
> typeof r
"function"
我知道 instanceof
,但这需要您事先知道类型。
I know of instanceof
, but this requires you to know the type beforehand.
> [1,2] instanceof Array
true
> r instanceof RegExp
true
还有更好的方法吗?
推荐答案
Angus Croll最近写了一篇有趣的博客文章 -
Angus Croll recently wrote an interesting blog post about this -
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof -operator /
他详细介绍了各种方法的优点和缺点,然后定义了一种新方法'toType' -
He goes through the pros and cons of the various methods then defines a new method 'toType' -
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
这篇关于获取Javascript变量类型的更好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文