在JS中有比typeof更好的方法来获取变量的类型吗?当你这样做时,它工作得很好:

> 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

有没有更好的办法?


当前回答

我们还可以改变ipr101中的一个小例子

Object.prototype.toType = function() {
  return ({}).toString.call(this).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

并调用as

"aaa".toType(); // 'string'

其他回答

YUI3使用的是一个相当不错的类型捕获函数:

var TYPES = {
    'undefined'        : 'undefined',
    'number'           : 'number',
    'boolean'          : 'boolean',
    'string'           : 'string',
    '[object Function]': 'function',
    '[object RegExp]'  : 'regexp',
    '[object Array]'   : 'array',
    '[object Date]'    : 'date',
    '[object Error]'   : 'error'
},
TOSTRING = Object.prototype.toString;

function type(o) {
    return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};

这捕获了javascript提供的许多原语,但您总是可以通过修改TYPES对象添加更多原语。注意,Safari中的typeof HTMLElementCollection将报告function,而type(HTMLElementCollection)将返回object

安格斯·克罗尔最近写了一篇有趣的博文

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()
}

https://npmjs.com/package/advanced-type

为此我创建了一个包。

您可以尝试使用constructor.name。

[].constructor.name
new RegExp().constructor.name

就像所有JavaScript一样,最终总会有人指出这在某种程度上是邪恶的,所以这里有一个链接,可以很好地回答这个问题。

另一种方法是使用Object.prototype.toString.call

Object.prototype.toString.call([])
Object.prototype.toString.call(/./)

我们还可以改变ipr101中的一个小例子

Object.prototype.toType = function() {
  return ({}).toString.call(this).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

并调用as

"aaa".toType(); // 'string'