Daily Archives: 2011/11/21

Get the real type in javascript

In javascript, we can use “type” function to get the type of an element (e.g “aa”, [], {}, 1, true, null, undefined, function, global), but get an array’s type. it returns a “object”. So, how to get the real type of the element?

USE “Object.prototype.toString.apply” function.

WHY?

Because any elements inherit it. Now, let’s see the results

Object.prototype.toString.apply("aa") //return [object String]
Object.prototype.toString.apply(1) //return [object Number]
Object.prototype.toString.apply({}) //return [object Object]
Object.prototype.toString.apply([]) //return [object Array]
Object.prototype.toString.apply(true) //return [object Boolean]
Object.prototype.toString.apply(null) //return [object Null]
Object.prototype.toString.apply(undefined) //return [object Undefined]
Object.prototype.toString.apply(window) //return [object global]
Object.prototype.toString.apply(Math.abs)//return [object Function]

//... and all