当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js的各种数据类型判断的介绍

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

2019年03月16日  | 移动技术网IT编程  | 我要评论

1.typeof

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]; 
  } 
  ........ 
}

总结

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网