随笔 - 148  文章 - 0  评论 - 13  阅读 - 21万

js判断数据类型的几种方式

一 typeof

回顾:js有五种基本数据类型:值类型("number","string","boolean","undefined") 和引用类型 (“object”),其中“object” 又包含“array,function,null”等数据类型。
typeof 可以判断所有的值类型"number","string","boolean","undefined"和引用类型中的‘function’ 类型,其余所有的引用类型都只能返回‘object’。
typeof 能返回6中数据类型。

type of 1;//"number"
type of 'test';//"string"
type of true;//"boolean"
type of undefined;//"undefined"
type of console.log;//"function"
type of null;//"object"
type of [];//"object"
type of {};//"object"

二 instanceof

优点:可以判断某个对象是否是由某个构造函数new 出来的 ,凡是通过构造函数创建的都能进行判断
例如:

//构造函数假如被当作普通函数直接执行抛出错误
function Person (){
    if(!(this instanceof Person)){  // 当Person被直接执行时,this在非严格模式下是指向window的,而被当作构造函数时,this 是指由Person new出来的对象
        throw new Error(‘Person为构造函数,请使用 new Person’);
    }
}

缺点:不能判断null 类型以及非new 出来的的值类型,不能精确的区分array、function和object

function utility(){
    return {
        isAarry:(data)=> data instanceof  Array,
        isFunction:()=> data instanceof Function
    }
}

三 Object.prototype.toString

优点:所有的数据类型都能判断
原理:一切皆对象
js 里面还有好多类型判断 [object HTMLDivElement] div 对象 , [object HTMLBodyElement] body 对象 ,object Document或者 [object HTMLDocument](firefox,google) ......各种dom节点的判断,这些东西在我们写插件的时候都会用到。

function utility(){
    return {
        isArray:(o)=>Object.prototype.toString.call(o) == "[object Array]",
        isObj:(o)=>Object.prototype.toString.call(o) == "[object Object]",
        isNull:(o)=>Object.prototype.toString.call(o) == "[object Null]",
        isFunction:(o)=>Object.prototype.toString.call(o) == "[object Function]",
        isDate:(o)=>Object.prototype.toString.call(o) == "[object Date]", 
        isDocument:(o)=>Object.prototype.toString.call(o) =="[object Document]"|| Object.prototype.toString.call(o) == "[object HTMLDocument]",
        isNumber:(o)=>Object.prototype.toString.call(o) == "[object Number]", 
        isString:(o)=>Object.prototype.toString.call(o) == "[object String]", 
        isUndefined:(o)=>Object.prototype.toString.call(o) == "[object Undefined]", 
        isBoolean:(o)=>Object.prototype.toString.call(o) == "[object Boolean]", 
    }
}
posted on   长安城下翩翩少年  阅读(724)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示