判断JS数据类型的方法

判断数据类型

1. typeof
  • 对于基本类型,除 null 以外,均可以返回正确的结果。

  • 对于引用类型,除 function 以外,一律返回 object 类型。

  • 对于 null ,返回 object 类型。

  • 对于 function 返回 function 类型。

  • typeof (123)//"number"
    typeof ("123")//"string"
    typeof ([1,2])//"object"
    typeof (null)//"object"
    typeof (function func(){}//"function"
    typeof Symbol()//"symbol"
    typeof new Date();  //object 无效
    typeof new RegExp();  //object 无效
    
2. instanceof
  • 用来判断A是否为B的实例:A instanceof B

  • instanceof 检测的是原型

  • instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。

    因果关系
    o3.__proto__ === M.prototype
    o3 instanceof M //true
    
    M.prototype._proto_ === Object.prototype //针对M来说
    o3 instanceof Object //true
    
  • instanceof 无法检测基本数据类型;

  • [] instanceof Array; //true
    {} instanceof Object;//true
    new Date() instanceof Date;//true
    new RegExp() instanceof RegExp//true
    null instanceof Null//报错
    undefined instanceof undefined//报错
    
3. toString

是object的原型方法

  • let arr = [1,2,3];
    			const func = function(){};
    			var data = new Date();
    			var string = "xuting" ;
    			var number = 2;
    			var nul = null;
    			var und = undefined;
    			var obj = {
    				A:1,
    				B:2
    			}
         	console.log(Object.prototype.toString.call(arr));//"[object Array]"
    			console.log(Object.prototype.toString.call(data));//"[object Date]"
    			console.log(Object.prototype.toString.call(func));//"[object Function]"
    			console.log(Object.prototype.toString.call(string));//"[object String]"
    			console.log(Object.prototype.toString.call(obj));//"[object Object]"
    			console.log(Object.prototype.toString.call(number));//"[object Number]"
    			console.log(Object.prototype.toString.call(nul));//"[object Null]"
    			console.log(Object.prototype.toString.call(und));//"[object Undefined]"
    

问题:那么为什么不使用数据类型自己本身的toString()方法呢

  • 因为所有类在继承Object方法时,会改写toString()方法
  • var arr = [1,2,3]
    
      console.log(arr.toString());//'1,2,3'
    
      console.log(Array.prototype.toString);//'1,2,3'
    
      delete Array.prototype.toString;//删除Array原型上的toString()方法
    
      //就会向上层访问这个方法,即Object的toString()方法
    
      console.log(arr.toString());//'[object Array]'
    
4. constructor
  • 当一个函数 F被定义时,JS引擎会为F添加 prototype 原型,然后再在 prototype上添加一个 constructor 属性,并让其指向 F 的引用

  • function b(){console.log(1)};
    b.prototype.constructor === b;   // true
    (123).constructor //Number(){}
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值