zoukankan      html  css  js  c++  java
  • 类型检测 Amy

    对变量的类型检测除了我们前面提到的typeof以外,还有instanceof操作符和constructor属性两种方法

    一、instanceof操作符

    虽然在检测基本数据类型时,typeof是非常得力的助手,但是在检测引用类型的值时,该操作符的用处不大,我们需要知道的不仅仅是它是一个对象,还想要知道它是一个什么类型的对象

    var r=new RegExp();
    var a=[];
    alert(r instanceof RegExp);//true
    alert(a instanceof Array);//true
    alert(2 instanceof Number);//false
    alert(null instanceof Object);//false
    //使用instanceof检测基本数据类型的值时,始终会返回false,instanceof操作符检测的是该对象是属于什么类型的对象
    function A(){}
    var d=new A();
    alert(d instanceof A);//true

    二、constructor属性

    该属性的功能涵盖了typeof和instanceof操作符

    var r=new RegExp();
    var a=[];
    alert(NaN.constructor==Number);//true
    alert(r.constructor
    ==RegExp);//true alert(a.constructor==Array);//true alert("".constructor==String);//true alert((2).constructor==Number);//true //alert(null.constructor==Object);//出错,undefined和null不能使用该属性,会提示null没有该属性,抛出异常 function A(){} var d=new A(); alert(d.constructor==A);//true
  • 相关阅读:
    大话领域驱动
    c#之循环效率
    编程思想之——"人是活的,程序是死的"
    C#之系统异常处理机制
    EF操作扩展之async
    C#提供APP接口之JSON差异
    EF操作MySql
    WCF 消息压缩性能问题及解决方法
    [NoSQL]-Elasticsearch 7.9
    [Linux]-Debian10基础使用
  • 原文地址:https://www.cnblogs.com/amy2011/p/3131815.html
Copyright © 2011-2022 走看看