1.typeof
typeof方法可以判断除了null以外的所有的基础数据类型以及function。
console.log(typeof 1) // number
console.log(typeof 'hello') // string
console.log(typeof undefined) // undefined
console.log(typeof true) // boolean
console.log(typeof Symbol()) // symbol
console.log(typeof null) // object
console.log(typeof function () { }) // function
console.log(typeof {}) // object
console.log(typeof []) // object
2.instanceof
typeof方法可以判断复杂数据类型,不能判断所有的基础数据类型。
console.log(1 instanceof Number) // false
console.log('hello' instanceof String) // false
console.log(true instanceof Boolean) // false
console.log(Symbol() instanceof Symbol) // false
console.log({} instanceof Object) // true
console.log([] instanceof Array) // true
console.log(function () { } instanceof Function) // true
console.log(null instanceof Null) // 报错
console.log(undefined instanceof Undefined) // 报错
3.Object.prototype.toString
Object.prototype.toString方法可以判断所有的数据类型,需要配合call()使用。
console.log(Object.prototype.toString.call(1)) // [object Number]
console.log(Object.prototype.toString.call('hello')) // [object String]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
console.log(Object.prototype.toString.call(Symbol())) // [object Symbol]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call([])) // [object Array]
console.log(Object.prototype.toString.call(function () { })) // [object Function]