JavaScript中的数据类型分为两类
基本数据类型 : String Number Boolean Undefined Null
引用数据类型 : Array Function Object
如何判断
1.typeof 运算符
const str = 'abc'
const num = 123
const bol = true
const und = undefined
const nul = null
const arr = [10,20,30]
const fn = function () {}
const object = { name : '小明' }
console.log( typeof str )//'string'
console.log( typeof num )//'number'
console.log( typeof bol )//'boolean'
console.log( typeof und )//'undefined'
console.log( typeof nul )//'object'
console.log( typeof arr )//'object'
console.log( typeof fn )//'function'
console.log( typeof str )//'object'
可以看出,typeof 有两种数据类型无法检测 null和数组无法检测,结果都是 'object'
2.Object.prototype.toString.call() 万能数据类型检测 (推荐使用)
const str = 'abc'
const num = 123
const bol = true
const und = undefined
const nul = null
const arr = [10,20,30]
const fn = function () {}
const object = { name : '小明' }
console.log(Object.prototype.toString.call(str))//[object String]
console.log(Object.prototype.toString.call(num))//[object Number]
console.log(Object.prototype.toString.call(bol))//[object Boolean]
console.log(Object.prototype.toString.call(und))//[object Undefined]
console.log(Object.prototype.toString.call(nul))//[object Null]
console.log(Object.prototype.toString.call(arr))//[object Array]
console.log(Object.prototype.toString.call(fn))//[object Function]
console.log(Object.prototype.toString.call(obj))//[object Object]
本质是使用call方法修改了toString中this的指向
3. instanceof 运算符
用于检测构造函数的prototype在不在实例对象的原型链中
const arr = [10,20,30]
const fn = function () {}
const object = { name : '小明' }
console.log( arr instanceof Array )//true
console.log( fn instanceof Function )//true
console.log( obj instanceof Object )//true
console.log( arr instanceof String )//false