zoukankan      html  css  js  c++  java
  • javascript 判断数据类型的几种方法

    javascript 判断数据类型的几种方法
    一、typeof 直接返回数据类型字段,但是无法判断数组、null、对象

    
    typeof 1
    "number"
    
    typeof NaN
    "number"
    
    typeof "1"
    "string"
    
    typeof true
    "boolean"
    
    typeof undefined
    "undefined"
    
    typeof null
    "object"
    
    typeof []
    "object"
    
    typeof {}
    "object"
    

    其中 null, [], {}都返回 "object"

    二、instanceof 判断某个实例是不是属于原型

    
    // 构造函数
    function Fruit(name, color) {
        this.name = name;
        this.color = color;
    }
    var apple = new Fruit("apple", "red");
    
    // (apple != null)
    apple instanceof Object  // true
    apple instanceof Array   // false
    

    三、使用 Object.prototype.toString.call()判断

    call()方法可以改变this的指向,那么把Object.prototype.toString()方法指向不同的数据类型上面,返回不同的结果

    
    Object.prototype.toString.call(1)
    "[object Number]"
    
    Object.prototype.toString.call(NaN);
    "[object Number]"
    
    Object.prototype.toString.call("1");
    "[object String]"
    
    Object.prototype.toString.call(true)
    "[object Boolean]"
    
    Object.prototype.toString.call(null)
    "[object Null]"
    
    Object.prototype.toString.call(undefined)
    "[object Undefined]"
    
    Object.prototype.toString.call(function a() {});
    "[object Function]"
    
    Object.prototype.toString.call([]);
    "[object Array]"
    
    Object.prototype.toString.call({});
    "[object Object]"
    

    最后我们可以定义一个完美的判断数据类型的方法 _typeof()

    
    function _typeof(obj){
      var s = Object.prototype.toString.call(obj);
      return s.match(/[object (.*?)]/)[1].toLowerCase();
    };
    
    
    _typeof([12,3,343]);
    "array"
    
    _typeof({name: 'zxc', age: 18});
    "object"
    
    _typeof(1);
    "number"
    
    _typeof("1");
    "string"
    
     _typeof(null);
    "null"
    
    _typeof(undefined);
    "undefined"
    
    _typeof(NaN);
    "number"
    
    _typeof(Date);
    "function"
    
    _typeof(new Date());
    "date"
    
    _typeof(new RegExp());
    "regexp"
    

    来源:https://segmentfault.com/a/1190000018160547

  • 相关阅读:
    字符串、组合数据类型练习
    使用python画五星红旗
    常用linux操作
    关于大数据
    简易C语言文法
    实验一 词法分析系统
    关于计算机编译原理
    七号团队-团队任务4:每日例会(2018-11-28)
    七号团队-团队任务4:每日例会(2018-11-27)
    第七组,团队作业2
  • 原文地址:https://www.cnblogs.com/qixidi/p/10390742.html
Copyright © 2011-2022 走看看