javascript 得到变量类型的函数
时间:2024-04-30 08:53:34
这个功能需要写一点代码来实现。下面的函数可以得到一个变量的类型,调用时传递一个变量进去,会返回用字符串形式描述的变量类型。
//得到x的类型,返回类型名称
function getType(x) {
//如果x为null,则返回null
if (x == null) return "null";
var t = typeof x;
//如果x为简单类型,则返回类型名称
if (t.toLocaleLowerCase() != "object") return t;
//调用object类的toString方法得到类型信息
//object.toString方法返回类似这样的信息[object 类名]
t = Object.prototype.toString.apply(x).toLowerCase();
//截取toString方法返回值的类名部分
t = t.substring(8, t.length - 1);
if (t.toLocaleLowerCase() != "object") return t;
//检查x确实为object类型
if (x.constructor == Object) return t;
//从构造函数得到类型名称
if (typeof x.constructor == "function")
return getFunctionName(x.constructor);
return "unknow type";
}
//得到函数名称
function getFunctionName(fn) {
if (typeof fn != "function") throw "the argument must be a function.";
var reg = /\W*function\s+([\w\$]+)\s*\(/;
var name = reg.exec(fn);
if (!name) {
return '(Anonymous)';
}
return name[1];
}
标签:javascript,变量类型
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现xml转json文件的示例代码
2023-09-29 23:52:50
jQuery模板提案
2010-03-30 18:27:00
企业网站FLASH引导页存在的意义
2008-06-04 11:09:00
python django入门
2022-05-10 02:46:19
![](https://img.aspxhome.com/file/2023/5/131105_0s.jpg)
PHP register_shutdown_function()函数的使用示例
2023-10-07 08:06:27
url地址栏加密和解密函数 Base64
2008-07-10 13:29:00
Python浅析生成器generator的使用
2023-09-02 16:58:40
python使用PIL模块获取图片像素点的方法
2022-07-28 10:57:57
Python多线程扫描端口代码示例
2021-09-26 10:32:39
使用Pandas的Series方法绘制图像教程
2023-12-12 17:52:25
![](https://img.aspxhome.com/file/2023/5/66305_0s.jpg)
使用django实现一个代码发布系统
2022-06-28 02:42:45
![](https://img.aspxhome.com/file/2023/4/65114_0s.png)
Python设计模式行为型观察者模式
2022-02-20 12:32:58
![](https://img.aspxhome.com/file/2023/0/133590_0s.png)
Django使用中间件解决前后端同源策略问题
2022-09-05 10:33:32
![](https://img.aspxhome.com/file/2023/3/71343_0s.png)
如何用python 操作MongoDB数据库
2024-01-27 16:53:10
python去除文件中重复的行实例
2022-07-30 17:33:38
初步解析Python中的yield函数的用法
2023-01-03 12:23:05
利用Python将彩色图像转为灰度图像的两种方法
2021-02-06 05:28:54
![](https://img.aspxhome.com/file/2023/8/120268_0s.jpg)
MySQL数据库之Purge死锁问题解析
2024-01-28 05:11:50
![](https://img.aspxhome.com/file/2023/9/121229_0s.jpg)
PHP set_time_limit(0)长连接的实现分析
2023-11-06 11:46:20
学习JSON.stringify的9大特性和转换规则
2024-04-23 09:29:12