1、js判断的数据类型
基本数据类型:Undefined、Null、Boolean、Number、String,Symbol
引用数据类型 :Objectlet bool = true; let num = 1; let str = 'abc'; let und= undefined; let nul = null; let arr = [1,2,3,4]; let obj = {name:'xiaoming',age:22}; let fun = function(){console.log('hello')}; let s1 = Symbol();
2.typeof
typeof 用来判断各种数据类型,有两种写法:typeof xxx , typeof(xxx)
typeof可以识别出基本类型boolean,number,undefined,string,symbol,但是不能识别null。不能识别引用数据类型,会把null、array、object统一归为object类型,但是可以识别出function。
所以typeof可以用来识别一些基本类型。typeof 2 输出 number typeof null 输出 object typeof {} 输出 object typeof [] 输出 object typeof (function(){}) 输出 function typeof undefined 输出 undefined typeof '222' 输出 string typeof true 输出 boolean
3.instanceof
判断已知对象类型的方法.instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。
var c= [1,2,3]; var d = new Date(); var e = function(){alert(111);}; function a(){this.name="22";}; console.log(c instanceof Array) //true console.log(d instanceof Date) //true console.log(e instanceof Function) //true console.log(a instanceof Function ) //true
4.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 在类继承时会出错
5.Object.prototype.toString.call
此方法可以相对较全的判断js的数据类型。
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]