• Js判断数据类型的4种⽅式


    1.Js判断数据类型的4种⽅式

    Js数据类型 es5 6种数据类型:string、number、boolean、object(Data、function、Array)、null、undefined
    Es6中新增了⼀种数据类型:symbol:表示独⼀⽆⼆的值,最⼤的⽤法是⽤来定义对象的唯⼀属性名,⽆论何时都不相等

    var s1 = Symbol("symbol");
    
    • 1

    1.typeof

    • 对于基本类型,除 null 以外,均可以返回正确的结果。
    • 对于引⽤类型,除 function 以外,⼀律返回 object 类型。
    • 对于 null ,返回 object 类型。
    • 对于 function 返回 function 类型。
      Typeof NaN = number
      Typeof null = object
      Typeof object = function Object/Array/String/Number/Boolean/Date/RegExp都是构造函数
      Typeof {} = object
      typeof console.log = ‘function’ 函数本身
      typeof console.log() = ‘undefined’ 运⾏函数,默认返回undefined
      2.instanceof
      测试A是否是B的实例,⽐较A._proto是否和B.prototype相等
      ,instanceof 只能⽤来判断两个对象是否属于实例关系, ⽽不能判断⼀个对象实例具体属于哪种类型。
      [] instanceof Array
      {} instanceof Object
    instanceof (A,B) = {
        var L = A.__proto__;
        var R = B.prototype;
        if(L === R) {
            // A的内部属性 __proto__ 指向 B 的原型对象
            return true;
        }
        return false;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3.constructor

    1. null 和 undefined 是⽆效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他⽅式来判断。
      ‘’.constructor === ‘String’
      New Number(1).constructor === ‘Number’
      New Function().constructor === ‘function’
      4.toString
      Object的原型⽅法,返回当前对象的[[Class]]
      Object.prototype.toString.call(‘’) // [[Object String]]
      Object.prototype.toString.call(new Error()) ; // [object Error]
      Object.prototype.toString.call(document) ; // [object HTMLDocument]
      Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引⽤
  • 相关阅读:
    大话机器学习准确率(Accuracy)、精确率(Pecision)、召回率(Recall)以及TP、FP、TN、FN
    C++PrimerPlus跟读记录【第五章】循环和关系表达式
    基于opencv实现简单人脸检测
    第一天-基本知识整理,目的:能写点东西
    室内定位UWB在化工园区如何智能化管理
    labelme安装
    qt 在下安装闪退 退出的解决方案
    ZMQ/ZeroMQ的三种消息模式
    高分三号1米分辨率飞机检测识别数据集
    编译 --> 链接
  • 原文地址:https://blog.csdn.net/weixin_38318244/article/details/125994222