zoukankan      html  css  js  c++  java
  • js 验证数据类型的4中方法

    1.typeof  可以检验基本数据类型 但是引用数据类型(复杂数据类型)无用;

    总结 : typeof  无法识别引用数据类型  包括 bull; 

    2.instanceof是一个二元运算符,左操作数是一个对象,右操作数是一个构造函数。如果左侧的对象是右侧构造函数的实例对象,则表达式返回true;否则返回false

      如果左操作数不是对象,返回false,如果右操作数不是函数,则抛出一个类型错误异常TypeError

      console.log(  true  instanceof Boolean)    // boolean
         console.log( "string" instanceof String)  // string
        console.log(   123 instanceof Number)    // number
        // console.log(  undefined instanceof   )  //语法错误
        console.log( function(){} instanceof  Function)  //function
        // console.log( null instanceof  null)     //语法错误
        console.log( [1,2,3] instanceof   Array)   //objet  
        console.log( {"name":"liming"} instanceof  Object )  // object

    总结 :null  和 undefined  没有构造函数 使用此方法会报错!!! 无法鉴别基本数据类型  并且引用数据类型全部为对象 !!!

    3.constructor

      实例对象的constructor属性指向其构造函数。如果是对象类型,则输出function 数据类型(){}; null  undefiend 报错

     4.Object.prototype.toString()方法

      对象的类属性是一个字符串,用以表示对象的类型信息。javascript没有提供设置这个属性的方法,但有一种间接方法可以查询它

      Object.prototype.toString()方法返回了如下格式的字符串:[object 数据类型]

    console.log(Object.prototype.toString.call("string"));//[object String]
    console.log(Object.prototype.toString.call(1));//[object Number]
    console.log(Object.prototype.toString.call(true));//[object Boolean]
    console.log(Object.prototype.toString.call(undefined));//[object Undefined]
    console.log(Object.prototype.toString.call(null));//[object Null]

  • 相关阅读:
    java web项目打包.war格式
    version 1.4.2-04 of the jvm is not suitable for thi
    Sugarcrm Email Integration
    sharepoint 2010 masterpage中必须的Content PlaceHolder
    微信开放平台
    Plan for caching and performance in SharePoint Server 2013
    使用自定义任务审批字段创建 SharePoint 顺序工作流
    Technical diagrams for SharePoint 2013
    To get TaskID's Integer ID value from the GUID in SharePoint workflow
    how to get sharepoint lookup value
  • 原文地址:https://www.cnblogs.com/shouzi/p/9225740.html
Copyright © 2011-2022 走看看