判断数据类型的方式
typeof(推荐指数***)
- typeof(123) //number
- typeof('hello') //string
- typeof(true) //boolean
- typeof(null) //object
- typeof(undefined) //undefined
- typeof(function(){}) //function
- typeof(Symbol()) //symbol
- typeof({color:'red'}) //object
- typeof([1,2,3]) //object
- typeof(new Date()) //object
特点
- typeof能判断基本类型
- typeof能判断函数
- typeof能判断symbol类型
- typeof无法区分null/普通对象/数组/日期对象等
_ _ proto _ _ (推荐指数*)
- [1,2,3]._ _ proto _ _===Array.prototype //true
- new Date()._ _ proto _ _===Date.prototype //true
特点
getPrototypeOf(推荐指数***)
- Object.getPrototypeOf([1,2,3])===Array.prototype //true
- Object.getPrototypeOf(new Date())===Date.prototype //true
- Object.getPrototypeOf(new Date())===Array.prototype //false
- Object.getPrototypeOf([1,2,3])===Date.prototype //false
特点
- 可以判断引用类型
- 功能其实与__proto__一致,只是写法不同
isPrototypeOf(推荐指数***)
- Array.prototype.isPrototypeOf([1,2,3]) //true
- Date.prototype.isPrototypeOf(new Date()) //true
特点
constructor(推荐指数*)
- ({color:'blue'}).constructor===Array //false
- ([1,2,3]).constructor===Array //true
特点
- constructor容易被修改,存在判断不准的情况
instanceof (推荐指数***)
- ({color:'blue'}) instanceof Object //true
- ({color:'blue'}) instanceof Array //false
- ([1,2,3]) instanceof Array //true
特点
Object.prototype.toString.call() (推荐指数*****)
- Object.prototype.toString.call({color:'red'}) //[object Object]
- Object.prototype.toString.call([1,2,3]) //[object Array]
- Object.prototype.toString.call(new Date()) //[object Date]
- Object.prototype.toString.call(Symbol()) //[object Symbol]
- Object.prototype.toString.call(function(){}) //[object Function]
- Object.prototype.toString.call(false) //[object Boolean]
- Object.prototype.toString.call(123) //[object Number]
- Object.prototype.toString.call('hello') //[object String]
- Object.prototype.toString.call(null) //[object Null]
- Object.prototype.toString.call(undefined) //[object Undefined]
特点
- 可判断任意类型
- 非常精确,当typeof判null的时候,得出的结果是object,但是此方法可以精准到null类型
- Object.prototype.toString.call(undefined).slice(8,-1).toLocaleLowerCase(),可以直接获取像typeof一样得到小写字符串类型。
Array.isArray()(推荐指数*****)
特点
- 专门判断对象是否为数组类型
- 内部也是使用Object.prototype.toString.call()方法封装的