码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 如何判断一个对象的类型

时间:2014-10-05 04:35:37      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   java   sp   div   

<!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 

 

javascript 如何判断一个对象的类型

标签:style   blog   color   io   os   ar   java   sp   div   

原文地址:http://www.cnblogs.com/ghgyj/p/4006648.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!