Fork me on GitHub

js使用typeof与instanceof相结合编写一个判断常见变量类型的函数

/**
 * 常见类型判断
 * @param {any} param 
 */
function getParamType(param) {
    // 先判断是否能用typeof 直接判断
    let types1 = ['number', 'string', 'boolean', 'undefined', 'symbol', 'function']
    let type = typeof param;
    type = types1.indexOf(type);
    if (type !== -1) {
        return types1[type]
    }
    // 剩余的用instanceof判断
    switch (true) {
        case param instanceof Date:
            return 'date'
        case param instanceof Array:
            return 'array'
        case param instanceof Object:
            return 'object'
        case null === param && !param:
            return 'null'    
        default:
            return 'can not judge'
    }
}


console.log(getParamType(1)); // number
console.log(getParamType('1')); // string
console.log(getParamType(true)); // boolean
console.log(getParamType(undefined)); // undefined
console.log(getParamType(Symbol.for(2))); // symbol
console.log(getParamType(() => 1)); // function
console.log(getParamType([])); // array
console.log(getParamType({})); // object
console.log(getParamType(new Date())); // date
console.log(getParamType(null)); // null
posted @   粥里有勺糖  阅读(180)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示