js 的数据类型及判断方法

一、数据类型的分类

 (1)数值类型(原始类型)

            string:字符串

            boolean:true/false

            number:数字

            undefined:undefined,代表变量已声明,但是还没有赋值

            null:null,代表变量已声明,但是赋值为null

 (2)对象类型(引用类型)

           Object:对象,用于存储多种类型的数据,对应一个事物,包含属性和方法

           Function :方法/函数,一种特殊的对象,类比于代码的封装,可执行,具有一定的功能性 

           Array :数组,一种特殊的对象,存储的数据有顺序

二、判断数据类型的方法

   (1)typeof 可用于判断数值类型

         a.判断string类型

           var str="早安"

           typeof str==="string"//true

        b.判断boolean类型

           var boo=false;

           typeof boo==="false"//true

        c.判断number类型

           var n=10

           typeof n==="number"//true

        d.判断undefined类型

           var undef=undefined

           typeof undef==="undefined"//true

           undef===undefined//true

          e.判断null类型

           var nu=null

           typeof nu==="null"//false,因为typeof nu=object,因此不能用typeof来判断

           nu===null//true

         f.typeof不能用来判断对象类型,除了function,均返回object

          var obj=new Object();

          function fn(){}

          var arr=[];

          typeof obj   //object

          typeof fn   //function

          typeof arr  //object

     (2)instanceof 用于判断对象类型

          var obj=new Object();

          function fn(){}

          var arr=[];

         obj instanceof Object  //true

         fn instanceof Function // true

         arr instanceof Array //true

     (3)constuctor

         obj.constructor===Object

         fn.constructor===Function

         arr.constructor===Array

        n.constructor===Number

        注意:constructor在类继承上会出错

        function fn1(){}

        function fn2(){}

        fn1.prototype=new fn2();//fn1继承自fn2

        var A=new fn1()

        A.constructor===fn1//false

        A.constructor===fn2//true

    (4)prototype通用方法

       Object.prototype.toString.call(n)==="[object Number]"//true

       Object.prototype.toString.call(arr)==="[object Array]"//true

       Object.prototype.toString.call(fn)==="[object Function]"//true

       ......

    (5)万能方法  jquery.type()

          jQuery.type(arr)==="array"

         jQuery.type(fn)==="function"

         jQuery.type(n)==="number"

         jQuery.type(undef)==="undefined"

          .......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值