zoukankan      html  css  js  c++  java
  • javascript类型判断方法

    判断javascript中的类型,共有四种常用的方法

    var a=6;

    var b="str";

    var c=true;

    var arr=[];

    typeof 用于基本类型的判断

    1.typeof最好用于基本类型的判断,返回类型名(小写)。

    例外 typeof null==="object" //true

    typeof function(){}==="function" //true

    2.typeof返回的是字符串

    3.对变量执行typeof操作

    得到的不是变量类型,而是变量值的类型,因为JS区别别的语言,变量没有类型,值才有。

    instanceof 已知对象类型,进而判断

    console.log(arr.constructor===Array);//true

    constructor 

    console.log(arr.constructor===Array);//true

    注意:

    constructor在类继承时会出错,instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true

    var A=function(){};

    var B=function(){};

    A.prototype=new B();

    var obj=new A();

    console.log(obj.constructor===B);//true

    console.log(obj.constructor===A)//false

    console.log(obj instanceof B)//true

    console.log(obj instanceof A)//true

    解决方法:obj.constructor = A;手动

    prototype 最通用方法

    Object.prototype.toString.call()

    console.log(Object.prototype.toString.call(a))//[object,Number]

  • 相关阅读:
    php开发_图片验证码
    php开发_php环境搭建
    中序线索二叉树算法
    WPF技巧(1)异步绑定
    WPF技巧(2)绑定到附加属性
    nhibernate 抓取策略
    wpf 控件开发基础(6) 单一容器(Decorator)
    WPF技巧(3)监测属性变更
    Caliburn v2 变更启动初始化
    wpf单容器中的Chrome
  • 原文地址:https://www.cnblogs.com/ziqian9206/p/6915158.html
Copyright © 2011-2022 走看看