详解js中typeof、instanceof与constructor

本文深入探讨JavaScript中的数据类型检测方法,包括使用typeof关键字和instanceof运算符的基本原理及应用场景。通过示例说明如何准确判断变量类型,特别是对于复杂类型如对象和数组的精确识别。

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

typeof返回一个表达式的数据类型的字符串,返回结果为js基本的数据类型,包括number,boolean,string,object,undefined,function.语法为typeof(data) 或 typeof data

instanceof则为判断一个对象是否为某一数据类型,或一个变量是否为一个对象的实例;返回boolean类型
语法为 o instanceof A

以下为综合实例:


复制代码
 1<script type="text/javascript">
 2<!
 3alert("typeof(1):" + typeof(1));//number
 4alert("typeof(\"abc\"):" + typeof("abc"));//string
 5alert("typeof(true):" +typeof(true));//boolean
 6alert("typeof(2009-2-4):" + typeof(2009-2-4));//number
 7alert("typeof(\"2009-2-4\"):" + typeof("2009-2-4"));//string
 8alert("typeof(m):" + typeof(m));//undefined
 9var d=new Date();
10alert("typeof(d):" + typeof(d));//object
11function Person(){};
12alert("typeof(Person):" + typeof(Person));//function
13var a=new Array();
14alert("typeof(a):" + typeof(a));//object
15alert("a instanceof Array:" + (a instanceof Array));
16var h=new Person();
17var o={};
18alert("h instanceof Person:" + (h instanceof Person));//true
19alert("h instanceof Object:" + (h instanceof Object));//true
20alert("o instanceof Object:" + (o instanceof Object));//true
21alert(typeof(h));//object
22//–>
23</script>
复制代码

js中constructor较少使用,如果不是搜索到相关construtor相关的资料,我之前从没有注意到js还有这个函数。

使用typeof的一个不好的地方就是它会把Array还有用户自定义函数都返回为object

复制代码
1<script type="text/javascript">
2<!
3var j=2;
4alert(typeof(j));//number
5alert("j.constructor:" + j.constructor);//function …
6alert(typeof(j.constructor));//function
7//–>
8</script>
复制代码


可以看到js.constructor返回的是一些字符串,大家都应该能看到这是一个function类型,此例为Number()为Number对象的构造函数,Number()用于将其参数转换为数字number类型,并返回转换结果(若不能转换则返回 NaN)。

因此在以后的js判断数据类型时可以使用以下方式来得到其详细数据类型

1if((typeof o=="object") && (o.constructor==Number)){
2
3}

这里还要注意,constructor只能对已有变量进行判断,而typeof则可对未声明变量进行判断(返回undefined)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值