• js中准确判断数据类型的方法


    一   通用的typeof 方法

           typeof  ture    输出   Boolean

           typeof  123   输出     number

             .....

           但是   typeof 无法判断  null    underfind     数组  和    对象类型    因为都返回    object 

    二、Object.prototype.toString.call();

    var   gettype=Object.prototype.toString

            gettype.call('aaaa')        输出      [object String]

            gettype.call(2222)         输出      [object Number]

            gettype.call(true)          输出      [object Boolean]

            gettype.call(undefined)  输出      [object Undefined]

            gettype.call(null)                  输出   [object Null]

             gettype.call({})                   输出   [object Object]

             gettype.call([])                    输出   [object Array]
             gettype.call(function(){})     输出   [object Function]

                封装一下

                       function   type(data){

                                   return Object.prototype.toString.call(data).slice(8,-1).toLowerCase;

                         }

    三   jQery.type()或者$.type();

    如果对象是undefined或null,则返回相应的“undefined”或“null”。

    jQuery.type( undefined ) === "undefined"

    jQuery.type() === "undefined" jQuery.type( window.notDefined ) === "undefined"

    jQuery.type( null ) === "null"

    如果对象有一个内部的[[Class]]和一个浏览器的内置对象的 [[Class]] 相同,我们返回相应的 [[Class]] 名字。  

    jQuery.type( true ) === "boolean"

    jQuery.type( 3 ) === "number"

    jQuery.type( "test" ) === "string"

    jQuery.type( function(){} ) === "function"

    jQuery.type( [] ) === "array"

    jQuery.type( new Date() ) === "date"

    jQuery.type( new Error() ) === "error" // as of

    jQuery 1.9 jQuery.type( /test/ ) === "regexp"

    其他一切都将返回它的类型“object”。

    四   还可以用  instanceof判断已知的对象类型的方法

          注意:instanceof 后面一定要是对象类型 ,并且大小写不能错,该方法适合一些条件选择和方法

          比如:   data.instanceof===Function   返回ture

               但: data.instanceof ===function  返回false

    五根据对象的constructor判断

                  data.constructor ===Array    返回布尔值

                  注意:constructor 在类继承时会出错

                eg:

    function A(){}; function B(){};

    A.prototype = new B(); //A继承自B var aObj = new A();

    alert(aobj.constructor === B) -----------> true;

    alert(aobj.constructor === A) -----------> false; 而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true:

    alert(aobj instanceof B) ----------------> true;

    alert(aobj instanceof B) ----------------> true;

    言归正传,解决construtor的问题通常是让对象的constructor手动指向自己:

    aobj.constructor = A; //将自己的类赋值给对象的constructor属性

    alert(aobj.constructor === A) -----------> true;

    alert(aobj.constructor === B) -----------> false; //基类不会报true了;

  • 相关阅读:
    Git Bash 下操作文件及文件夹命令
    python django -2 ORM模型
    python django -1
    redis python交互和实际例子
    MongoDB API和python操作
    python mysql 封装
    fabric 自动化部署
    linux 开机自启
    linux shell习题训练
    linux grep sed awk
  • 原文地址:https://www.cnblogs.com/shuaishuaidejun/p/6558280.html
Copyright © 2020-2023  润新知