JavaScript typeof obj === ‘object’ 这样写有什么问题

本文介绍了JavaScript中使用typeof关键字判断变量类型的局限性,并提供了更准确的判断方法:利用constructor属性和instanceof运算符来精确判断变量是否属于特定的对象类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typeof Array, Object, new Class() 都会返回'object', 所以使用typeof不能准确的判断变量是否为object

typeof [];  //object
typeof {};  //object
typeof new (function (){});  //object
typeof 1//number
typeof '1'//string
typeof null//object
typeof true//boolean
 
 要准确判断一个变量是否是一个对象,可以使用constructor以及instanceof判断。
1. constructor是指该对象的构造函数, 使用constructor时, 要注意, 实例化类时, 类的prototype.constructor需要正确引用。
({}).constructor === Object;  //true
(1).constructor === Number;  //true
([]).constructor === Array;  //true
('1').constructor === String;  //true
(true).constructor === Boolean;  //true

 

2. instanceof是指该对象是否为指定类的实例
({}) instanceof Object;  //true
([]) instanceof Array;   //true
(1) instanceof Number;  //true
('1') instanceof String;  //true
(true) instanceof Boolean;  //true

 

转载于:https://www.cnblogs.com/facial/p/5797629.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值