• javascript 判断数据类型的方法


    javascript 判断数据类型的方法

    1. typeof

    1. 只能判断基础类型数据
    2. 遇到Object、Array、Null都会被判断为Object
    
    // 基本数据类型
     console.log(typeof 2);               // number
     console.log(typeof true);            // boolean
     console.log(typeof 'str');           // string  
     console.log(typeof function(){});    // function
     console.log(typeof undefined);       // undefined
    
    //  引用数据类型
    console.log(typeof {});              // object
    console.log(typeof []);              // object    
    console.log(typeof null);            // object
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2. instanceof

    1. instanceof可以正确地判断对象类型
    2. instanceof不能判断普通类型
    // 基本数据类型
     console.log(2 instanceof Number);                    // false
     console.log(true instanceof Boolean);                // false 
     console.log('str' instanceof String);                // false 
      
    // 引用数据类型
     console.log([] instanceof Array);                    // true
     console.log(function(){} instanceof Function);       // true
     console.log({} instanceof Object);                   // true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3. constructor

    1. 这种方法需要通过通过原型访问到构造函数,如果这个数据的原型被修改了,这个方法就行不通
     console.log((2).constructor === Number); // true
     console.log((true).constructor === Boolean); // true
     console.log(('str').constructor === String); // true
     console.log(([]).constructor === Array); // true
     console.log((function() {}).constructor === Function); // true
     console.log(({}).constructor === Object); // true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4. Object.prototype.toString.call()

    1. 通过对象原型上的的toString方法可以判断类型
    2. 使用 .call() 是因为 Array 和 Function 数据类型重写了 .toString方法.
    3. 只有原来的对象的toString方法才能判断类型。
    
     let a = Object.prototype.toString;
      
     console.log(a.call(2));                 //[object Number]
     console.log(a.call(true));              //[object Boolean]
     console.log(a.call('str'));             //[object String]
     console.log(a.call([]));                //[object Array]
     console.log(a.call(function(){}));      //[object Function] 
     console.log(a.call({}));                //[object Object]
     console.log(a.call(undefined));         //[object Undefined]
     console.log(a.call(null));              //[object Null]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    相关文章

    参考文章@笨成要先飞

  • 相关阅读:
    数据结构HW2
    前后端分离&vue简介
    内容安全实验——实验一 硬盘分区恢复实践
    yolov7和yolov5对比有哪些优势?yolov7改进-yolov7详解
    python实现图像二分类精准率(numpy)
    DiskPressure(磁盘压力)
    振南技术干货集:振南当年入门C语言和单片机的那些事儿(5)
    Word目录中自动添加自定义样式的多级标题的方法
    【LeetCode】55. 跳跃游戏 - Go 语言题解
    利用nginx发布静态服务
  • 原文地址:https://blog.csdn.net/i_Satan/article/details/126732849