在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

有没有更好的办法?


当前回答

你可以将object .prototype. tostring应用于任何对象:

var toString = Object.prototype.toString;

console.log(toString.call([]));
//-> [object Array]

console.log(toString.call(/reg/g));
//-> [object RegExp]

console.log(toString.call({}));
//-> [object Object]

这在所有浏览器中都工作得很好,除了IE -当调用从另一个窗口获得的变量时,它会吐出[object object]。

其他回答

我想这里最通用的解决方案是首先检查undefined和null,然后调用constructor.name.toLowerCase()。

const getType = v =>
  v === undefined
    ? 'undefined'
    : v === null
      ? 'null'
      : v.constructor.name.toLowerCase();




console.log(getType(undefined)); // 'undefined'
console.log(getType(null)); // 'null'
console.log(getType('')); // 'string'
console.log(getType([])); // 'array'
console.log(getType({})); // 'object'
console.log(getType(new Set())); // `set'
console.log(getType(Promise.resolve())); // `promise'
console.log(getType(new Map())); // `map'

您可以尝试使用constructor.name。

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

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

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

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

我做了这个函数:

(您应该将其命名为更唯一的,这样它就不会与其他全局名称冲突。)

function type(theThing) {
    return Object.prototype.toString.call(theThing).match(/\s([\w]+)/)[1].toLowerCase()
}
type({})           //-> 'object'
type([])           //-> 'array'
type(function(){}) //-> 'function'
    
type(null)         //-> 'null'
type(undefined)    //-> 'undefined
type(true)         //-> 'boolean'
type('hello')      //-> 'string'
type(42)           //-> 'number'

type(Symbol())     //-> 'symbol'
type(/abc/)        //-> 'regexp'
type(new Set())    //-> 'set'
// etc ...

PS:上面的F.NiX做了更健壮的版本,它还告诉你从Class或构造函数中创建的自定义对象的名称。

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

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

并调用as

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

Typeof条件用于检查变量类型,如果你在if-else条件下检查变量类型 如。

if(typeof Varaible_Name "undefined")
{

}