2010.10.14——— typeof instanceof

本文详细介绍了JavaScript中typeof和instanceof的区别与用法。typeof用于返回变量的数据类型字符串,而instanceof则判断一个变量是否为特定对象的实例。文章通过示例展示了它们如何帮助开发者进行类型检查。

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

2010.10.14——— typeof instanceof

参考:[url]http://blog.youkuaiyun.com/fisea/archive/2010/06/01/5640329.aspx[/url]
[url]http://blog.sina.com.cn/s/blog_532751d90100iv1r.html[/url]

typeof 和 instanceof 常用来判断一个变量是否为空,或者是什么类型的。

[b]1.typeof [/b]

typeof返回值是一个字符串,该字符串说明运算数的类型。typeof 一般只能返回如下几个结果:
[color=red]number,boolean,string,function,object,undefined。[/color]

对于 Array,Null 等特殊对象使用 typeof 一律返回 object,这正是 typeof 的局限性


<script language="javascript" type="text/javascript">
document.write ("typeof(1): "+typeof(1)+"<br>");
document.write ("typeof(NaN): "+typeof(NaN)+"<br>");
document.write ("typeof(Number.MIN_VALUE): "+typeof(Number.MIN_VALUE)+"<br>");
document.write ("typeof(Infinity): "+typeof(Infinity)+"<br>");
document.write ("typeof(\"123\"): "+typeof("123")+"<br>");
document.write ("typeof(true): "+typeof(true)+"<br>");
document.write ("typeof(window): "+typeof(window)+"<br>");
document.write ("typeof(Array()): "+typeof(new Array())+"<br>");
document.write ("typeof(function(){}): "+typeof(function(){})+"<br>");
document.write ("typeof(document): "+typeof(document)+"<br>");
document.write ("typeof(null): "+typeof(null)+"<br>");
document.write ("typeof(eval): "+typeof(eval)+"<br>");
document.write ("typeof(Date): "+typeof(Date)+"<br>");
document.write ("typeof(sss): "+typeof(sss)+"<br>");
document.write ("typeof(undefined): "+typeof(undefined)+"<br>")
</script>



[b]2 instanceof[/b]

instanceof 用于判断一个变量是否某个对象的实例,如 var a=new Array();alert(a instanceof Array); 会返回 true,同时 alert(a instanceof Object) 也会返回 true;这是因为 Array 是 object 的子类。再如:function test(){};var a=new test();alert(a instanceof test) 会返回true

另外 说一下function 的 arguments,我们知道它不是数组 其实可以用instanceof来判断一下 就知道了


[b]区别:[/b]
1. 返回类型不一样 

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

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

2. instanceof 测试的 object 是指 js 语法中的 object,不是指 dom 模型对象 而typeof 是都可以的

if (window instanceof Object) alert('Y');else alert('N');
得'N'
alert(typeof(window)) 会得 object
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值