判断数据类型的三种方式

77 阅读1分钟

typeof

优点:使用简单

缺点:只能判断6中基本数据类型

typeof == 基本数据类型

Object.prototype.toString.call

优点:可以判断所有数据类型

缺点:使用上相对typeof繁琐

let type = Object.prototype.toString.call(['1','2'])
type === '[object Array]' //true

instanceof

只能判断构造函数的prototype属性是否出现在某个实例对象的原型链上

class Person{
    constructor(name,age){
        this.name = name,
        this.age = age
    }
}
let p = new Person('a',1)
console.log(p instanceof Person)//true