zoukankan      html  css  js  c++  java
  • 判断各种数据类型的方法总结

    1.typeof 

    type of  ...判断数据类型

    number返回number

    string返回string

    boolean返回boolean

    undefined返回undefined

    null返回object

    function返回function

    object返回object

    array返回object

    NAN返回number

    2.instanceof

    检查某对象是否属于某类型

    instanceof是通过原型链来检查类型的,所以适用于任何”object”的类型检查。

     3.toString

         

         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]

        4. constructor也能判断数据类型:

         如:    

     ''.constructor==String    
    
     [].constructor==Array
    
     var obj= new Object()   obj.constructor==Object

    检查所有数据类型的方法

    function checkType (obj) {
         return Object.prototype.toString.call(obj).slice(8,-1)
    }    

    类型检测总结

    ==typeof==只能检测基本数据类型,对于null还有Bug;
    ==instanceof==适用于检测对象,它是基于原型链运作的;
    ==constructor==指向的是最初创建者,而且容易伪造,不适合做类型判断;
    ==Object.prototype.toString==适用于ECMA内置JavaScript类型(包括基本数据类型和内置对象)的类型判断;
    基于引用判等的类型检查都有跨窗口问题,比如instanceof和constructor。
    总之,如果你要判断的是基本数据类型或JavaScript内置对象,使用toString; 如果要判断的时自定义类型,请使用instanceof。

  • 相关阅读:
    vuex 数据持久化
    vue中通过第三方代理解决跨域问题
    谷歌浏览器格式化插件
    mongodb安装配置
    Nodejs express中创建ejs项目
    elementui tree 组件实现鼠标移入节点,节点后面显示添加删除按钮
    iframe页面无法跳转问题
    elementui table组件,根据数据的不同,显示不同的内容
    elementui tree组件自定义图标
    Aborting a running program
  • 原文地址:https://www.cnblogs.com/baixiaoxiao/p/12322591.html
Copyright © 2011-2022 走看看