JS中数据类型的判断

66 阅读1分钟

typeof

typeof常被用来进行基本数据类型的判断。

console.log(typeof 1) // number
console.log(typeof NaN) // number
console.log(typeof 'aaa') // string
console.log(typeof true) // boolean
console.log(typeof undefined) // undefined

console.log(typeof []) // object
console.log(typeof {}) // object

使用typeof判断{}[]的时候,返回的都是object,所以无法判断到底是数组还是对象。

instanceof

instanceof可以用来进行引用数据类型的判断。

需要指定类型来判断。

console.log([] instanceof Array) // true
console.log({} instanceof Object) // true

如何更精准的判断类型呢?可以借助toString方法;

toString()方法返回一个表示该对象的字符串

toString.call(1) // '[object Number]'
toString.call('aaa') // '[object String]'
toString.call(true) // '[object Boolean]'
toString.call(undefined) // '[object Undefined]'
toString.call(null) // '[object Null]'
toString.call([]) // '[object Array]'
toString.call({}) // '[object Object]'
toString.call(new Date()) // '[object Date]'
toString.call(function(){}) // '[object Function]'