目录
前言
记录点js基础,js的类型分类以及判断方法,typeof()的用法问题,以及使用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 );
精准判断
- 想要精准判断类型,建议使用
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] );