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
  • 相关阅读:
    获取非行间样式
    获取非行间样式
    prompt 方法显示输入对话框
    comfirm 方法显示对话框
    移动端页面常见问题及解决方案
    原生js怎样获取后台端口数据
    canvas描绘渐变的矩形
    cookie 的增加,销毁,读取
    canvas 绘制图形
    数组的排序,去重复
  • 原文地址:https://www.cnblogs.com/amy2011/p/3131815.html
Copyright © 2011-2022 走看看