原生JS常用类型判断方法

泛用方法

typeof

typeof 运算符更适用于判断基本数据类型,会返回下列6种类型之一:
"number","string","boolean","object","function","undefined"
typeof 会把 null 归为 object,且无法判断除 function 之外的其它复杂数据类型
注:typeof 返回的是字符串,且均为小写

typeof test === 'string'

instanceof

用于判断是否为某一种数据类型(判断是否为某种对象的实例),返回 true 或 false
注:instanceof 后面必须是对象类型且以大写字母开头,无法判断 null,undefined 和 NaN

"string" instanceof String

constructor

对象的 constructor 属性中存有其构造函数,用于判断其是否为某一种构造函数的实例(与 instanceof 相近)

var a = []
a.constructor === Array         //  true
a.constructor === Object          // false

类似的用原型判断的方法还有

arr.__proto__  === Array.prototype

注意:constructor在类继承时会出错,如下情景

functionA(){}
functionB(){}
A.prototype = new B()               //  A继承自B
var aObj = new A()
alert(aObj.constructor === B)          //  true
alert(aObj.constructor === A)          //  false

解决方法:让对象的 constructor 手动指向自己

aObj.constructor = A             //  将自己的类赋值给对象的constructor属性
alert(aObj.constructor === B)          //  false
alert(aObj.constructor === A)          //  true

Object.prototype.toString.call()

通用性强而且准确,call() 会将 this 指向括号里传入的对象,查找其 prototype 并转换为字符串

Object.prototype.toString.call(a) === '[object String]'               //  true
Object.prototype.toString.call(null)                                           //  '[object Null]'
Object.prototype.toString.call(undefined)                                 //  '[object Undefined]'
Object.prototype.toString.call(NaN)                                         //  '[object NaN]'

下面是简洁的封装,来自vue源码

var _toString = Object.prototype.toString
function toRawType (value) {
    return _toString.call(value).slice(8, -1)
}


专用方法

Array.isArray

es6新增的方法,返回 true 或 false

Array.isArray(arr)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容