网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

js的各种数据类型判断的介绍

1.typeof

创新互联公司2013年至今,是专业互联网技术服务公司,拥有项目成都做网站、成都网站制作网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元额敏做网站,已为上家服务,为额敏各地企业和个人服务,联系电话:18982081108

typeof 用来判断各种数据类型,有两种写法:typeof xxx , typeof(xxx)

例如:

typeof 2 输出 number 
typeof null 输出 object 
typeof {} 输出 object 
typeof [] 输出 object 
typeof (function(){}) 输出 function 
typeof undefined 输出 undefined 
typeof '222' 输出 string 
typeof true 输出 boolean

这里面包含了js里面的五种数据类型 number、string、boolean、 undefined、object 和函数类型 function

2. instanceof

判断已知对象类型的方法.instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。

  var c= [1,2,3]; 
  var d = new Date(); 
  var e = function(){alert(111);}; 
  var f = function(){this.name="22";}; 
  console.log(c instanceof Array) //true
  console.log(d instanceof Date) //true
  console.log(e instanceof Function) //true
  // console.log(f instanceof function ) //false

3.constructor

根据对象的constructor判断,返回对创建此对象的数组函数的引用。

var c= [1,2,3]; 
var d = new Date(); 
var e = function(){alert(111);}; 
alert(c.constructor === Array) ----------> true 
alert(d.constructor === Date) -----------> true 
alert(e.constructor === Function) -------> true 
//注意: constructor 在类继承时会出错

4.prototype

所有数据类型均可判断:Object.prototype.toString.call

这是对象的一个原生原型扩展函数,用来更精确的区分数据类型。

var gettype=Object.prototype.toString
gettype.call('aaaa') 输出 [object String] 
gettype.call(2222) 输出 [object Number] 
gettype.call(true) 输出 [object Boolean] 
gettype.call(undefined) 输出 [object Undefined] 
gettype.call(null) 输出 [object Null] 
gettype.call({}) 输出 [object Object] 
gettype.call([]) 输出 [object Array] 
gettype.call(function(){}) 输出 [object Function]

其实js 里面还有好多类型判断 [object HTMLDivElement] div 对象 , [object HTMLBodyElement] body 对象 ,[object Document](IE)或者 [object HTMLDocument](firefox,google) ……各种dom节点的判断,这些东西在我们写插件的时候都会用到。

可以封装的方法如下:

var gettype=Object.prototype.toString 
var utility={ 
  isObj:function(o){ 
    return gettype.call(o)=="[object Object]"; 
  }, 
  isArray:function(o){ 
    return gettype.call(o)=="[object Array]"; 
  }, 
  isNULL:function(o){ 
    return gettype.call(o)=="[object Null]"; 
  }, 
  isDocument:function(){ 
    return gettype.call(o)=="[object Document]"|| [object HTMLDocument]; 
  } 
  ........ 
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对创新互联的支持。如果你想了解更多相关内容请查看下面相关链接


网页标题:js的各种数据类型判断的介绍
本文来源:http://bjjierui.cn/article/ishggi.html

其他资讯