js数据类型检测总结
在js中,有四种用于检测数据类型的方式,分别是:
- typeof 用来检测数据类型的运算符
- instanceof 检测一个实例是否属于某个类
- constructor 构造函数
- object.prototype.tostring.call() 原型链上的object对象的tostring方法
下面我们就来分别介绍一下上面四种方法的适用场景和局限性。
typeof 用来检测数据类型的运算符
使用typeof检测数据类型,返回值是字符串格式。能够返回的数据类型
是:"number","string","bolean","undefined","function","object"。
<script> console.log(typeof(1)); //number console.log(typeof('hello')); //string console.log(typeof(true)); //boolean console.log(typeof(undefined)); //undefined console.log(typeof(null)); //object console.log(typeof({})); //object console.log(typeof(function() {})); //function </script>
局限性:
- typeof (null); //"object"。这是由于在js中,null值表示一个空对象指针,而这也正是使用typeof操作 符检测null值时会返回"object"的原因。
- 不能具体的细分是数组还是正则,还是对象中其他的值,因为使用typeof检测数据类型,对于对象数据类型的所有的值,最后返回的都是"object"
instanceof 检测某一个实例是否属于某个类
instanceof主要用来弥补typeof不能检测具体属于哪个对象的局限性。
<script> let arr = [1,2,3]; let reg = /\w/; console.log(arr instanceof array); //true console.log(arr instanceof object); //true console.log(reg instanceof regexp); //true console.log(reg instanceof object); //true </script>
局限性:
- 不能用于检测和处理字面量方式创建出来的基本数据类型值,即原始数据类型
- instanceof的特性:只要在当前实例的原型链上的对象,我们用其检测出来都为true
- 在类的原型继承中,我们最后检测出来的结果未必正确
constructor 构造函数
是函数原型上的属性,该属性指向的是构造函数本身。
作用和instsnceof非常相似,与instanceof不同的是,不仅可以处理引用数据类型,还可以处理原始数据类型。
<script> let num = 12; let obj = {}; console.log(num.constructor == number);//true console.log(obj.constructor == object);//true </script>
但是要注意一点的是,当直接用(对象字面量或原始数据).constructor时,最好加上()。为了便于理解,我们来看一个例子。
<script> 1.constructor === number; //报错,invalid or unexceped token (1).constructor === number; //true {}.constructor === number; //报错,invalid or unexceped token ({}).constructor === number; //true </script>
这主要是由于js内部解析方式造成的,js会把1.constructor解析成小数,这显然是不合理的,小数点后应该是数字,因此就会引发报错。js会把{}解析成语句块来执行,这时后面出现一个小数点显然也是不合理的,因此也会报错。为了解决这个问题,我们可以为表达式加上()使js能够正确解析。
局限性:我们可以把类的原型进行重写,在重写的过程中很可能把之前constructor给覆盖了,这样检测出来的结果就是不准确的
<script> function fn() {}; fn.prototype = new array; var f = new fn; //f是一个函数,按道理说他的构造函数应该是function,但是修改其原型链后,它的constructor变成了array. console.log(f.constructor == array); //true </script>
object.prototype.tostring.call() 原型链上的object对象的tostring方法
object.prototype.tostring的作用是返回当前方法的执行主体(方法中的this)所属类的详细信息,是最全面也是最常用的检测数据类型的方式。
返回值的类型为string类型。
<script> console.log(object.prototype.tostring.call(1)); //[object number] console.log(object.prototype.tostring.call(/^sf/)); //[object regexp] console.log(object.prototype.tostring.call("hello")); //[object string] console.log(object.prototype.tostring.call(true)); //[object boolean] console.log(object.prototype.tostring.call(null)); //[object null] console.log(object.prototype.tostring.call(undefined)); //[object undefined] console.log(object.prototype.tostring.call(function() {})); //[object function] console.log(typeof(object.prototype.tostring.call(function() {}))); //string </script>
上一篇: 详解正则表达式实现二代身份证号码验证
下一篇: iconfont的三种使用方式详解