你知道检测对象类型吗的区别吗

基本类型的检测

typeof

var a = null;
typeof a //object

var =;
typeof u //undefined

instanceof
(1)对于引用类型可以检测 但是对于原始数据类型就不是很友好 只能检测出来一部分 只能检测出来那些通过new出来的原始数据类型
解释:instanceof 是通过原型链来识别 所以对于基本数据类型 只有通过new出来的对象才能识别

let str = 'hh'
let str2 = new String('hhh')
str instanceof String // false
str2 instanceof String // true

在这里插入图片描述

(2)对于引用类型还是友好的

var c = new Date();
c instanceof Object //true

var v = new RegExp();
v instanceof RegExp //true

引用类型的检测

引用类型如果还用typeof检测的话就都是object 没有办法分清楚对象数组等,因此引用类型不能用typeof。
Object.prototype.toString.call(null) 最好

1.判断基本类型:

Object.prototype.toString.call(null);//”[object Null]”
Object.prototype.toString.call(undefined);//”[object Undefined]”
Object.prototype.toString.call(“abc”);//”[object String]”
Object.prototype.toString.call(123);//”[object Number]”
Object.prototype.toString.call(true);//”[object Boolean]”
2.判断原生引用类型:

函数类型
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”
日期类型
var date = new Date();
Object.prototype.toString.call(date);//”[object Date]”
数组类型
var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”
正则表达式
var reg = /[hbc]at/gi;
Object.prototype.toString.call(arr);//”[object RegExp]”
自定义类型
function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(person); //”[object Object]”
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值