基本数据类型:Undefined、Null、Boolean、Number、String 复杂数据类型 :Object ( Object 类型、Array 类型、Date 类型、RegExp 类型、Function 类型等) ES6新增数据类型:Symbol
1.typeof 返回的是一个字符串,表示对象的数据类型,全部以小写表示

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