首页 > 代码库 > javascript 如何判断一个对象的类型
javascript 如何判断一个对象的类型
<!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:26undefined type.html:27null type.html:28undefined type.html:29undefined type.html:30undefined
javascript 如何判断一个对象的类型
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。