JS中判断数据类型的方法

JS中判断数据类型的方法

在小肉包的上一篇博客分享一波很全的 JS 判断数据类型的方法的基础上,再分享一个更综合的方法,与上一篇分享内容的不同之处在于,这篇中,只需要申明一个方法,就可以用于判断多种数据类型。


代码如下:
/**
 * 判断某个数据是否为某种类型
 * by 小肉包
 * @params type    想要判断的类型 
 * @params value    想要判断的数据
 * 返回值 :布尔值(true / false)
 */
 function belongTo(type, value) {
    
    
            switch (type) {
    
    
                case Number:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Number]'
                    }
                case Boolean:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Boolean]'
                    }
                case String:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object String]'
                    }
                case Array:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Array]'
                    }
                case Object:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Object]'
                    }
                case Function:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Function]'
                    }
                case null:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Null]'
                    }
                case undefined:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Undefined]'
                    }
                case Date:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Date]'
                    }
                default:
                    {
    
    
                        return false;
                    }
            }
        }

//使用举例:
console.log( belongTo(Number, 52) )      // true 

console.log( belongTo(String, '这是字符串吗') )      // true 

let arr = [1,5,12]
let a=500

console.log( belongTo(Array, arr) )      // true 

console.log( belongTo(String, a) )      // false

希望能给小伙伴们带来帮助哟!欢迎访问我的个人博客歌洞章

猜你喜欢

转载自blog.csdn.net/weixin_47160442/article/details/112874278