JS 判断数据类型
众所周知JS的数据类型原来有七种,ES2020 引入了一种新的数据类型 BigInt(大整数),所以共有8种
使用typeof
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /**5个基本**/ console.log( typeof 'str' ) // > string console.log( typeof 1) // > number console.log( typeof true ) // > boolean console.log( typeof Symbol()) // > symbol console.log( typeof 123n) // > bigint /**2个空**/ /*undefined未定义,变量不存在或者变量定义后没赋值*/ console.log( typeof undefined) // > undefined /*null*/ 存在变量,但是值被赋予了 null (空) console.log( typeof null ) // > object /**对象类型**/ console.log( typeof {}) // > object console.log( typeof []) // > object console.log( typeof function (){}) // > function |
可以看到,对于5个基本类型和undefined使用时效果正常,其他都效果不佳。
Object.prototype.toString.call()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | let [ string, number, boolean, symbol, bigint, unde, nu, object, array, fun ] = [ 'string' , 1, true , Symbol(), 123n, undefined, null , {}, [], function (){}] let value = [string,number,boolean,symbol,bigint,unde,nu,object,array,fun] value.forEach((ele) => { let toString = Object.prototype.toString.call(ele) console.log(toString) }) // [object String] // [object Number] // [object Boolean] // [object Symbol] // [object BigInt] // [object Undefined] // [object Null] // [object Object] // [object Array] // [object Function] |
我们可以看到,Object.prototype.toString.call()的方法返回的字符串可以稳定的得出是何种数据类型。
用是否为目标构造函数实例的方式判断类型
instanceof 已知对象类型来用(查到父级和以上)
1 2 3 4 | console.log(object instanceof Object) console.log(fun instanceof Function) console.log(array instanceof Array) // 都为true |
只能用于对象类型的判断
constructor,(查到父级结束)
1 2 3 | console.log(array.constructor === Array) // true console.log(object.constructor === Object) // true console.log(fun.constructor === Function) // true |
也可以对Date日期等类型使用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话