js判断的数据类型typeof instanceof constructor Object.prototype.toString.call

1、js判断的数据类型

基本数据类型:Undefined、Null、Boolean、Number、String,Symbol
引用数据类型 :Object

let 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]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值