本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前言
记录js的类型分类以及判断方法,typeof、instanceof的用法以及存在的问题,最后介绍使用Object.prototype.toString.call()精准判断类型的方法。
js类型
-
js有许多种
内置类型
,其中内置类型又分为两类,基本数据类型
和复杂==对象(Object)类型
。 -
基本数据类型:
Null
、Undefined
、Number
、String
、Boolean
、Symbel
、BigInt
。(截至2022/2/16,将来或许会引入更多的基本数据类型,就像Symbel、BigInt就是比较新引入的,原来只有五大基本数据类型)
typeof
- 测试基本数据类型:记结论,除了null会被判断为object其他基本类型都可以判断出来,因此不能用于判断
null
。console.log( typeof null,// object typeof 123,//或 Number(123),// number typeof undefined,// undefined typeof "str",//或 String('str'),// string typeof true,//或 Boolean(true)// boolean typeof Symbol(1),// symbol typeof 12345678910n,//或 BigInt(12345678910),// bigint ); 复制代码
- 测数组、对象、内置对象、new函数声明对象、函数等复杂对象类型:记结论,除了函数会被正确判断为function,其他全是object,因此不能用于判断
除了函数之外
的复杂的类型,都不能用typeof区分开来。console.log( typeof [],//object typeof {},//object typeof Math,//object typeof new String(),//object typeof (() => {}),//function ); 复制代码
instanceof
-
首先明确instanceof不能判断基本数据类型,且不能直接尝试得到你想要判断的内容的类型,只能够尝试判断是否是某种类型。
-
我们能够使用它去判断是否是某个复杂对象类型。
console.log(
[] instanceof Array, //true
{} instanceof Object, //true
new Date() instanceof Date, //true
(() => {}) instanceof Function, //true
)
复制代码
- 因为它的原理是原型链,所以存在一个问题,就是Object的原型作为原型链的终点,js的复杂类型本质也都是对象,因此判断他们是否是对象,也都为true。
console.log(
[] instanceof Object, //true
{} instanceof Object, //true
new Date() instanceof Object, //true
(() => {}) instanceof Object, //true
)
复制代码
精准判断
- .想要精准判断类型,建议使用
Object.prototype.toString.call()
。console.log( Object.prototype.toString.call(null), //[object Null] Object.prototype.toString.call("123"), //[object String] Object.prototype.toString.call(123), //[object Number] Object.prototype.toString.call(undefined), //[object Undefined] Object.prototype.toString.call(true), //[object Boolean] Object.prototype.toString.call(Symbol(1)), //[object Symbol] Object.prototype.toString.call(BigInt(1)), //[object BigInt] Object.prototype.toString.call(() => {}), //[object Function] Object.prototype.toString.call([]), //[object Array] Object.prototype.toString.call({}), //[object Object] Object.prototype.toString.call(Math), //[object Math] Object.prototype.toString.call(new String()) //[object String] ); 复制代码
尾言
如果觉得文章对你有帮助的话,欢迎点赞收藏哦,有什么错误或者意见建议也可以留言,感谢~