First,
Sometimes I write something to judge the type. When I test it, I really can't praise the type judgment in the native and jQuery. So I write a good type judgment, which is generally enough.
1 function test(type) { 2 if(type === null || type === undefined) { 3 return type; 4 } 5 // If it is an object, enter it to judge, otherwise it is the basic data type 6 else if (type instanceof Object) { // js Object judgement, Because typeof Can not judge null object,So we can only judge in advance and complement each other 7 if(type instanceof Function) { 8 return 'Function'; 9 }else if(type instanceof Array) { 10 return 'Array'; 11 } else if(type instanceof RegExp){ 12 return 'RegExp'; 13 }else if(type instanceof Date) { 14 return 'Date'; 15 } 16 // Judge whether it is node object or not JQuery Object, very useful,Novices generally don't know what type is 17 else if(type instanceof Node){ 18 return 'Node'; 19 }else if(type instanceof jQuery){ 20 return 'jQuery'; 21 } 22 else{ 23 return 'Object'; 24 } 25 } 26 // Basic data type 27 else { 28 return typeof type; 29 } 30 }
Two,
There are many restrictions on native code,
typeof can only judge the basic data type plus undefied, Function. null will be judged as object, and object and Array will be judged as object.
instanceof can only judge objects
===Can judge null, undefined.
Only by combining the above three methods can we judge these basic types. I have added several other types of judgment, which are good tools for novices and veterans. Hope you like it!