一:typeof
typeof对于基本数据类型,可以直接判断,如
typeof 1 // “number”
typeif “1” // “string”
但是对于复合数据类型,除了函数以外,都会返回 object,如
typeof [] // “object”
typeof {} // “object”
typeof function() {} // “function”
对于null和undefined
typeof null // “object”
typeof undefined // “undefined”
二:constructor
constructor,是每个原型上都会有的属性,指向关联的原型对象
“”.constructor == String // true
[].constructor == Array // true
new Function().constructor == Function // true
但是对于null和undefined,没有constructor,无法判断
三:Object.prototype.toString.call()
toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。
对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。
Object.prototype.toString.call(’’) ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]