javascript 如何判断一个对象的类型
2024-10-18 21:39:46
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var class2type = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]' : 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regexp',
'[object Object]' : 'object',
'[object Error]' : 'error'
};
function type( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
};
function Foo() {}
function Bar() {}
Bar.prototype = new Foo();
var foo = new Foo();
var bar = new Bar();
console.log(type(''));
console.log(type(undefined));
console.log(type(null));
console.log(type(true));
console.log(type(false));
console.log(type(1));
console.log(type(0));
console.log(type(new String('foo')));
console.log(type(new Number(10)));
console.log(type({}));
console.log(type(new Date()));
console.log(type(new Error()));
console.log(type([1,2,3] ));
console.log(type(new Array(1, 2, 3)));
console.log(type(new Function("") ));
console.log(type(/abc/g));
console.log(type(new RegExp("meow")));
console.log(type(new Object()));
console.log(type(foo));
console.log(type(bar));
console.log(type(/abc/g));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var class2type = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]' : 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regexp',
'[object Object]' : 'object',
'[object Error]' : 'error'
};
function type( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
};
console.log(typeof null);
console.log(class2type[ toString.call(null) ] );
console.log(type(null));
console.log(typeof undefined);
console.log(class2type[ toString.call(undefined) ] );
console.log(type(undefined));
</script>
</body>
</html>
object type.html:26
undefined type.html:27
null type.html:28
undefined type.html:29
undefined type.html:30
undefined
最新文章
- js转盘抽奖
- DailyRollingFileAppender的使用
- 判断密文加密类型hash-identifier
- DNX概述
- java学习笔记 (1) —— Strut2.3.24环境搭建
- WordPress插件制作教程(三): 添加菜单的方法
- 项目中Spring注入报错小结
- 6天通吃树结构—— 第三天 Treap树
- Smarty 注册变量
- python机器学习实战(一)
- 循环语句for,while,until,select
- Java经典编程题50道之十九
- mvvm,如何解析一个指令表达式?
- 【Python】 发邮件用 smtplib &; email
- window.open模拟表单POST提交
- Nginx location配置详解
- JqGrid把数据行插入指定位置的方法addRowData
- 如何将jar包添加到maven本地仓库
- Linux下不同颜色文件的类型
- EM算法求高斯混合模型參数预计——Python实现