获取 Javascript 变量类型的更好方法? [英] Better way to get type of a Javascript variable?

查看:23
本文介绍了获取 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆