首页 技术 正文
技术 2022年11月15日
0 收藏 529 点赞 3,819 浏览 1377 个字

今天在看相应的javascript书籍时,遇到了typeof和instanceof的问题,一直不太懂,特地查资料总结如下:

JavaScript 中 typeof 和 instanceof 常用来判断是什么类型的。但它们之间还是有区别的:

typeof

typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。

它返回值是一个字符串,该字符串说明运算数的类型。typeof 一般只能返回如下几个结果:

number,boolean,string,function,object,undefined。

先看例子:

var a= 1;
console.log(typeof a); //numbervar b= '1';
console.log(typeof b); //stringvar c;
console.log(typeof c); //undefinedvar d= true;
console.log(typeof d); //booleanvar e= [1,2,3];
console.log(typeof e); //objectvar f= function(){};
console.log(typeof f); //function

【插一句:注意一点,返回值number, string, undefined, function,boolean,object这些都是字符串,类型都是string。】

上面我们看到:

观察输出结果发现,number, string, undefined, function,boolean类型均能通过typeof方法判断,而array类型输出object。

因为typeof方法只能判断基本类型类型有(number, string, undefined,boolean,function【函数】),而当判断NULL,数组,对象这三种的情况时,一般都返回object。

除此之外(包括Date, RegExp,null等都只是object的扩展!),返回的都是object。

我们可以使用typeof来获取一个变量是否存在,如if(typeof a!=”undefined”){},而不要去使用if(a)因为如果a不存在(未声明)则会出错, 对于 Array,Null 等特殊对象使用 typeof 一律返回 object,这正是 typeof 的局限性。

正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时,或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof。

instanceof

instance:实例,例子

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。

另外,更重的一点是 instanceof 可以在继承关系中用来判断一个实例是否属于它的父类型。

有关instanceof的详细用法可参考:http://www.studyofnet.com/news/175.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,965
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,486
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,331
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,114
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,747
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,781