说说据你所知能够判断数据类型的几种方法

说说据你所知能够判断数据类型的几种方法

  • typeof

    const a = []
    console.log(typeof a);  //Object
    

    它只能判断基本数据类型,比如number、string、undefined、boolean、object、symbol

    它对于对象类型是返回 ' object '

    console.log(typeof NaN);输出的是 number

    console.log(typeof xxx函数);输出的是 function

    console.log(typeof null);输出的是object。

    console.log(Object.prototype.toString.call(null));才是输出 null

  • Object.prototype.toString.call()

    Object.prototype.toString.call() 更加全面,它既能判断基本数据类型,也能判断复杂数据类型。返回值是:所属的类

    在 Number、String、Boolean、Array、Function、这些类的原型上都重写了 Object 中的 toString()方法,重写为 将本身的值转为字符串

    JS中的类型主要分为两大类:原生类型和对象类型,总共来说是八种(面试只答这8种)

    原生类型:null/number/string/boolean/undefined/symbol/bigInt
    对象类似:object

    console.log(typeof null);  //object
    console.log(null instanceof Object);  //false
    //null 是个特例,虽然第一行代码在输出上是 object,但是它绝对是原生类型
    

    判断原生类型,我们通常用 typeof 关键字。判断对象类型,我们用 toString() 方法

    console.log(Object.prototype.toString.call(new Object));
    console.log(Object.prototype.toString.call(new Function));
    console.log(Object.prototype.toString.call(new Array));
    //像这种内置的构造函数可以不用写括号
    

    这个方法基本上都能判断,除了实例new Student()之类的

    class Person {
    
    }
    const p =new Person()
    console.log(Object.prototype.toString.call(p));  //[object Object]
    
  • instanceof

    首先我先讲个题外话

    1、java中的instanceof应用场景

    	假如有两个类Student、Teacher都继承了Person,现在有一个方法`test(Person p)`但是我不知道究竟传的是`new Student()`还是`new Teacher()`,这时候就需要判断一下了,如果`p instanceof Student`为真,那么这个p就是Student的实例,反亦。
    
    	不难看出,java中的instanceof代表:该引用是否是xxx的实例
    
    	注意:这里与继承没有半毛钱关系!
    

    2、js中的instanceof应用场景

    	假如有`a instanceof Array`,并且`a`是数组,那么就为真。因为`a`是数组,所以肯定能够调用数组原型身上的方法,所以在`a`的原型链上肯定`Array`
    
    	js中的instanceof代表:xxx的原型链上是否有它
    
const a = []
console.log(a instanceof Array);  //true

但是它存在一些弊端,因为原型链是可以修改的,比如

const a = {}
a.__proto__ = new Array()
console.log(a instanceof Array);  //true
//其实从这里可以看出,java和js中的instanceof其实是一样的,都是看是否是它的实例
//其实说白了a就是实例
  • constructor
const a = []
console.log(a.__proto__.constructor === Array);  //true
//通过constructor指回构造函数,从而得知是Array类型
//不难看出,像Object、Array这些都是构造函数,它们可以结合new关键字使用,但是像这些自带的应该可以省略new
  • Array.isArray()(判断数组推荐用这个,官方推荐)

    const a = []
    console.log(Array.isArray(a));  //true
    

相关链接:Javascript讲解系列之一Prototype原型链 - 百度文库 (baidu.com)

posted @ 2022-06-16 17:12  朱在春  阅读(799)  评论(0编辑  收藏  举报