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 的局限性
[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]
参考:[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