转载!javascript3种检测变量类型的方法

来源:互联网 发布:网络歌手陈柯 编辑:程序博客网 时间:2024/06/16 11:46

出处http://www.cnblogs.com/PolarisSky/p/5276483.html

1、typeof检测变量类型

typeof检测变量类型只能返回:number、string、boolean、undefined、function、symbol、object这七种值,可以用来判断基本数据类型,但对于判断引用类型来说还不够具体。这里需要注意的是对于函数、null的typeof检测结果。

1 console.log(typeof 1);//number2 console.log(typeof "a");//string3 console.log(typeof true);//boolean4 console.log(typeof undefined);//undefined5 console.log(typeof (function func(){}));//function6 console.log(typeof Symbol())//symbol7 console.log(typeof null);//object8 console.log(typeof {});//object

2、instanceof检测变量类型

1 console.log({} instanceof Object);//true2 console.log([] instanceof Array);//true3 console.log([] instanceof Object);//true4 console.log((function func(){}) instanceof Function);//true5 console.log((function func(){}) instanceof Object);//true6 console.log(/a{3}/gi instanceof RegExp);//true7 console.log(/a{3}/gi instanceof Object);//true
复制代码

instanceof只可以用来判断引用类型变量的具体类型,不可以用来判断基本数据类型(如果使用instanceof操作符检测基本数据类型的值,则该操作符返回结果始终都是false)。使用instanceof时,只要后面的数据类型处于引用类型变量所属类型的原型链上,结果都将返回true。所有引用类型的值都是Object实例,所以所有引用类型变量的instanceof Object都将返回true。

3、constructor检测变量类型

对于所有引用类型的变量,都有一个属性constructor,该属性指向该引用类型的构造函数。当然,constructor不能用于基本数据类型的类型检测。
1 console.log({}.constructor===Object);//true2 console.log([].constructor===Array);//true3 console.log([].constructor===Object);//false4 console.log((function func(){}).constructor===Function);//true5 console.log((function func(){}).constructor===Object);//false6 console.log((/a{3}/gi).constructor===RegExp);//true7 console.log((/a{3}/gi).constructor===Object);//false
复制代码



原创粉丝点击