• javascript 类型的判断


    在平常写js代码,类型判断必不可少,那么我们常见有哪几种?看到了标题,先不看你会想到那些方法 ,常用呢些呢?那么今天我自己总结一些判断类型的判断,如有错,万望告知!

    1:typeof 常用这种方法不错

    console.log(typeof 123 === "number"); //true
    
    console.log(typeof "type" === "string"); //true
    
    console.log(typeof undefined === "undefined"); //true
    
    console.log(typeof function(){} === "function"); //true
    //可是这两个就无法判断 都是"object"  console.log(typeof {} === "object"); //true  console.log(typeof [] === "object"); //true //注意 用typeof 判断 null 或是 [] 无法通过console.log(typeof null === "null") 没有标准值比较因此无法通过 ===  typeof [] // "object" type null // "undefined" 或是"object" 总之不同浏览器判断 都有变化 ,奇葩的null

    2: instanceof 来补充上面无法真正分辨出 数组 [] 与 json对象{} 。感觉instanceof 为了判断 [] {}而生的!!!

     console.log([] instanceof Array)//true
    
     console.log({} instanceof Object)//true

    // 判断其他的就功力下降了
    console.log(123 instanceof Number);//false
    console.log("type" instanceof String);//false
     

    3:toString.call() 这种方法不错 与 老祖宗方法 Object.prototype.toString.call()一样的 个人推荐用这种

     console.log(toString.call(123) === '[object Number]');//true
     console.log(toString.call('type') === '[object String]');//true
     console.log(toString.call(null) === '[object Null]');//true
     console.log(toString.call(undefined) === '[object Undefined]');//true
     console.log(toString.call(true) === '[object Boolean]');//true
     console.log(toString.call([]) === '[object Array]');//true
     console.log(toString.call({}) === '[object Object]');//true
     console.log(toString.call(function(){}) === '[object Function]');//true

    4:constructor 构造函数的属性  用来判别对创建实例对象的函数的引用(个人觉得:认爹妈用的)

            var arr = [];
            var str = 'type';
            var num = 123;
            var boo = true;
            var fn = function () {};
            var obj = {};
           
    console.log(arr.constructor == Array);//true
    console.log(str.constructor == String);//true
    console.log(num.constructor == Number);//true
    console.log(boo.constructor == Boolean);//true
    console.log(fn.constructor == Function);//true
    console.log(obj.constructor == Object);//true

    5:还有ES6的,或是jQuery就不列举了!!知道有这几种也足够使用了。。。

    上面判断的全都是内置对象实例后的类型判断,那么大家应该知道类型判断,日后GET起来,希望对你有用!!!深夜放毒,才是更有问道。。。

  • 相关阅读:
    【Devops】 Kubernetes 入门与基础
    【Devops】 DevOps基础与理念
    【Maven】 关于Maven,测试需要掌握的一些知识点
    【转】IntelliJ IDEA中Maven插件无法更新索引
    【Python】 RobotFramework 安装配置与简要操作
    【SpringBoot】 项目中运用的一些技巧,mybatis-plus 自动编译等(持续更新)
    Spring5源码分析(019)——IoC篇之解析alias标签、import标签和beans标签
    Spring5源码分析(018)——IoC篇之解析bean标签:注册解析的BeanDefinition
    Spring5源码分析(017)——IoC篇之解析bean标签:解析默认标签中的自定义标签
    Java学习驿站——Mark
  • 原文地址:https://www.cnblogs.com/l-yabiao/p/6637774.html
Copyright © 2020-2023  润新知