1. typeof
对于基本类型, 除了null
以外都可以正确显示
typeof 1 // 'number'
typeof 'string' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object', 这是历史遗留问题
对于对象, 除了函数外都显示 object
typeof [] // 'object'
typeof {} // 'object'
typeof function a(){} // 'function'
2. Object.prototype.toString.call()
通过调用Object
原型上的toString
方法, 返回一个[Object type]
的字符串
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('1') // "[object String]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call(function () {}) // "[object Function]"