分享

数据类型判断

 头号码甲 2020-02-15

基本数据类型:Undefined、Null、Boolean、Number、String
复杂数据类型 :Object ( Object 类型、Array 类型、Date 类型、RegExp 类型、Function 类型等)
ES6新增数据类型:Symbol

1.typeof  返回的是一个字符串,表示对象的数据类型,全部以小写表示
image.png

typeof 1 //输出number

typeof null //输出object

typeof {} //输出 object

typeof [] //输出 object

typeof (function(){}) //输出 function

typeof undefined //输出 undefined 

typeof '111' //输出 string 

typeof true //输出 boolean

typeof对于判断基本的数据类型很有用, 但不能识别null,都把它统一归为object类型

2. instanceof  用来判断 A 是否为 B 的实例,只能用来判断引用数据类型, 并且大小写不能错

var n= [1,2,3];

var d = new Date();

var f = function(){alert(111);};

console.log(n instanceof Array) //true

console.log(d instanceof Date) //true

console.log(f instanceof Function) //true

// console.log(f instanceof function ) //false

3.constructor  指向对象的构造函数 —— 不推荐使用

var n = [1,2,3];

var d = new Date();

var f = function(){alert(111);};

alert(n.constructor === Array) ----------> true

alert(d.constructor === Date) -----------> true

alert(f.constructor === Function) -------> true

//注意: constructor 在类继承时会出错

4.prototype 所有数据类型均可判断:Object.prototype.toString.call
这是对象的一个原型扩展函数,用来更精确的区分数据类型。

var gettype=Object.prototype.toString

gettype.call('a') \\ 输出 [object String]

gettype.call(1) \\ 输出 [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];
  }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多