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

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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值