JS判断变量的具体数据类型封装函数

封装函数为:

复制代码
//返回传入值的数据类型
function GetValueType(val) {
    var type = typeof val
    // object需要使用Object.prototype.toString.call判断
    if (type === 'object') {
        var typeStr = Object.prototype.toString.call(val)
        // 解析[object String]
        typeStr = typeStr.split(' ')[1]
        type = typeStr.substring(0, typeStr.length - 1)
    }
    return type
}
复制代码

 

原理解释如下:

JS中的typeof方法可以查看数据的类型,如下:

复制代码
复制代码
1 console.log(typeof 2); // number
2 console.log(typeof "2"); // string
3 console.log(typeof true); // boolean
4 console.log(typeof [2]); // object
5 console.log(typeof {name:2});// object
6 console.log(typeof function(){return 2});// function
7 console.log(typeof new Date());// object
8 console.log(typeof null); // object
9 console.log(typeof undefined);// undefined
复制代码
复制代码

但typeof只能区分数字、字符串、布尔值、方法及undefined,其他的对象、数组、日期、null等均为object,还是没能区分开,

我们可以利用Object.prototype.toString.call实现。

复制代码
复制代码
 1 var getType = Object.prototype.toString;
 2 var res = getType.call(2);
 3 res = getType.call("2");
 4 res = getType.call(true);
 5 res = getType.call([2]);
 6 res = getType.call({name:2});
 7 res = getType.call(function(){});
 8 res = getType.call(new Date());
 9 res = getType.call(null);
10 res = getType.call(undefined);
复制代码
复制代码

输出结果依次为:

复制代码
复制代码
1 [object Number]
2 [object String]
3 [object Boolean]
4 [object Array]
5 [object Object]
6 [object Function]
7 [object Date]
8 [object Null]
9 [object Undefined]
复制代码
复制代码

这样就能具体区分JS中的数据类型了。

 

posted on   itjeff  阅读(49)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2017-11-16 Enum,Int,String的互相转换 枚举转换
2016-11-16 RabbitMQ基础概念详细介绍

导航

< 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
点击右上角即可分享
微信分享提示