Javascript typeof与instanceof的区别
作者:lqh 时间:2024-06-07 15:53:47
JavaScript 中 typeof 和 instanceof 常用来判断一个变量是否为空,或者是什么类型的。但它们之间还是有区别的:
typeof
typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。
它返回值是一个字符串,该字符串说明运算数的类型。typeof 一般只能返回如下几个结果:
number,boolean,string,function,object,undefined。我们可以使用 typeof 来获取一个变量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 因为如果 a 不存在(未声明)则会出错,对于 Array,Null 等特殊对象使用 typeof 一律返回 object,这正是 typeof 的局限性。
instanceof
instance:实例,例子
a instanceof b?alert("true"):alert("false"); //a是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) 会返回
谈到 instanceof 我们要多插入一个问题,就是 function 的 arguments,我们大家也许都认为 arguments 是一个 Array,但如果使用 instaceof 去测试会发现 arguments 不是一个 Array 对象,尽管看起来很像。
另外:
测试 var a=new Array();if (a instanceof Object) alert('Y');else alert('N');
得'Y'
但 if (window instanceof Object) alert('Y');else alert('N');
得'N'
所以,这里的 instanceof 测试的 object 是指 js 语法中的 object,不是指 dom 模型对象。
使用 typeof 会有些区别
alert(typeof(window)) 会得 object
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用AJAX的一个简单的例子
Pycharm及python安装详细步骤及PyCharm配置整理(推荐)
![](https://img.aspxhome.com/file/2023/9/76019_0s.jpg)
python爬虫基础之urllib的使用
仿china.nba.com焦点图轮播展示效果(ie6,ff)
微信公众平台开发教程③ PHP实现微信公众号支付功能图文详解
![](https://img.aspxhome.com/file/2023/9/102089_0s.png)
python解析中国天气网的天气数据
关于MySQL索引的几点值得注意的事项
Python函数的迭代器与生成器的示例代码
![](https://img.aspxhome.com/file/2023/4/121494_0s.png)
Python爬虫:通过关键字爬取百度图片
![](https://img.aspxhome.com/file/2023/9/70019_0s.png)
python 绘图模块matplotlib的使用简介
![](https://img.aspxhome.com/file/2023/9/93809_0s.png)
小记一次mysql主从配置解决方案
![](https://img.aspxhome.com/file/2023/1/128071_0s.png)
GO语言入门Golang进入HelloWorld
![](https://img.aspxhome.com/file/2023/7/127427_0s.gif)
避免重复写代码的小函数
![](https://img.aspxhome.com/file/UploadPic/20089/21/2008921134758493s.gif)
详解PHP的引用计数
js自定义弹框插件的封装
![](https://img.aspxhome.com/file/2023/8/123428_0s.gif)
Java+swing+Mysql实现商品销售管理系统
![](https://img.aspxhome.com/file/2023/2/76272_0s.png)
Django如何与Ajax交互
python打印n位数“水仙花数”(实例代码)
MySQL下载安装详情图文教程
![](https://img.aspxhome.com/file/2023/5/69155_0s.jpg)