typeof VS instanceof 详解,判断JavaScript数据类型

instanceof 运算符用来检测 constructor.prototype是否存在于参数 object 的原型链上。

typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // 'object'
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false 
1.对于简单的内建类型使用typeof:
'example string' instanceof String; // false
typeof 'example string' == 'string'; // true

'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false

(function() {}) instanceof Function; // true
typeof function() {} == 'function'; // true

typeof 对于原始类型来说,除了 null 都可以显示正确的类型
在这里插入图片描述1
typeof 对于对象来说,除了函数都会显示 'object'
1

2.对于复杂的内建类型使用instanceof:
/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // 'object'

[] instanceof Array; // true
typeof []; // 'object'

{} instanceof Object; // true
typeof {}; // 'object'

在 JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 null 代表的是空指针(大多数平台下值为 0x00),因此,null的类型标签是 0,typeof null === 'object'

【总结】至于在真实的项目中什么时候使用它们进行数据类型比较,这取决于你要检查的可能数据类型。

如果变量可能未定义,使用typeof比较好。

typeof undefinedVariable //  "undefined"
undefinedVariable instanceof Object // throws an exception

如果变量可能为null,使用instanceof比较好。

var myNullVar = null;
typeof myNullVar; 			// "object" 
myNullVar instanceof Object; // false
3.判断JavaScript数据类型最准确的方法

我们用Object.prototype.toString的方法可以准确的判断数据类型:
obj.toString
Object.prototype.toString返回值是一个字符串,字符串里的内容固定格式为[object 判断类型的结果],前一个object全小写,后面的返回结果的首字母大写。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值