在js中,有四种用于检测数据类型的方式,分别是:
- typeof 用来检测数据类型的运算符
- instanceof 检测一个实例是否属于某个类
- constructor 构造函数
- .prototype.toString.call() 原型链上的 对象的toString方法
下面我们就来分别介绍一下上面四种方法的适用场景和局限性。
typeof 用来检测数据类型的运算符
使用typeof检测数据类型,返回值是字符串格式。能够返回的数据类型
是:"number","string","bolean","undefined","function"," "。
< >
console.log(typeof(1)); //number
console.log(typeof('hello')); //string
console.log(typeof(true)); //boolean
console.log(typeof(undefined)); //undefined
console.log(typeof(null)); //
console.log(typeof({})); //
console.log(typeof(function() {})); //function
</ >
局限性:
- typeof (null); //" "。这是由于在js中,null值表示一个空对象指针,而这也正是使用typeof操作 符检测null值时会返回" "的原因。
- 不能具体的细分是数组还是正则,还是对象中其他的值,因为使用typeof检测数据类型,对于对象数据类型的所有的值,最后返回的都是" "
instanceof 检测某一个实例是否属于某个类
instanceof主要用来弥补typeof不能检测具体属于哪个对象的局限性。
< > let arr = [1,2,3]; let reg = /\w/; console.log(arr instanceof Array); //true console.log(arr instanceof ); //true console.log(reg instanceof RegExp); //true console.log(reg instanceof ); //true </ >
局限性:
- 不能用于检测和处理字面量方式创建出来的基本数据类型值,即原始数据类型
- instanceof的特性:只要在当前实例的原型链上的对象,我们用其检测出来都为true
- 在类的原型继承中,我们最后检测出来的结果未必正确
constructor 构造函数
是函数原型上的属性,该属性指向的是构造函数本身。
作用和instsnceof非常相似,与instanceof不同的是,不仅可以处理引用数据类型,还可以处理原始数据类型。
< >
let num = 12;
let obj = {};
console.log(num.constructor == Number);//true
console.log(obj.constructor == );//true
</ >
但是要注意一点的是,当直接用(对象字面量或原始数据).constructor时,最好加上()。为了便于理解,我们来看一个例子。
< >
1.constructor === Number; //报错,Invalid or unexceped token
(1).constructor === Number; //true
{}.constructor === Number; //报错,Invalid or unexceped token
({}).constructor === Number; //true
</ >
这主要是由于js内部解析方式造成的,js会把1.constructor解析成小数,这显然是不合理的,小数点后应该是数字,因此就会引发报错。js会把{}解析成语句块来执行,这时后面出现一个小数点显然也是不合理的,因此也会报错。为了解决这个问题,我们可以为表达式加上()使js能够正确解析。
局限性:我们可以把类的原型进行重写,在重写的过程中很可能把之前constructor给覆盖了,这样检测出来的结果就是不准确的
< >
function Fn() {};
Fn.prototype = new Array;
var f = new Fn;
//f是一个函数,按道理说他的构造函数应该是Function,但是修改其原型链后,它的constructor变成了Array.
console.log(f.constructor == Array); //true
</ >
.prototype.toString.call() 原型链上的 对象的toString方法
.prototype.toString的作用是返回当前方法的执行主体(方法中的this)所属类的详细信息,是最全面也是最常用的检测数据类型的方式。
返回值的类型为string类型。
< >
console.log( .prototype.toString.call(1)); //[ Number]
console.log( .prototype.toString.call(/^sf/)); //[ RegExp]
console.log( .prototype.toString.call("hello")); //[ String]
console.log( .prototype.toString.call(true)); //[ Boolean]
console.log( .prototype.toString.call(null)); //[ Null]
console.log( .prototype.toString.call(undefined)); //[ Undefined]
console.log( .prototype.toString.call(function() {})); //[ Function]
console.log(typeof( .prototype.toString.call(function() {}))); //string
</ >
继续阅读与本文标签相同的文章
上一篇 :
DoS漏洞月份
下一篇 :
签名驱动程序打开对firmware的访问
-
Spring-boot-admin之HttpTrace显示入参和出参及增加Redisson监控
2026-05-17栏目: 教程
-
遇到API安全问题怎么办?F5 API加固解决方案怎么样?
2026-05-17栏目: 教程
-
Dubbo ZookeeperRegistry分析
2026-05-17栏目: 教程
-
有一种糖叫语法糖【9】IOT实践之物联网世界的鸡毛信message
2026-05-17栏目: 教程
-
阿里云上实现全站https最佳实践(一)
2026-05-17栏目: 教程
