<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>比较完整的数据类型安全检测方法</title> <script src="test.js"></script> <script> var a = Math.abs; alert(typeOf(a)); var a = null alert(typeOf(a)); var a = "abc"; alert(typeOf(a)); var b = [1,2,3]; alert(typeOf(b)); var b = false; alert(typeOf(b)); </script> </head> <body> </body> </html>
==========test.js==========
1 //安全检测JavaScript基本数据类型和内置对象 2 //参数:o表示检测的值 3 /*返回值:返回字符串"undefined"、"number"、"boolean"、 4 "string"、"function"、"regexp"、"array"、"date"、 5 "error"、"object"或"null" 6 */ 7 function typeOf(o){ 8 var _toString = Object.prototype.toString; 9 //获取对象的toString()方法引用 10 //列举基本数据类型和内置对象类型,可以进一步补充该数组的检测数据类型范围 11 var _type = { 12 "undefined":"undefined", 13 "number":"number", 14 "boolean":"boolean", 15 "string":"string", 16 "[object Function]":"function", 17 "[object RegExp]":"regexp", 18 "[object Array]":"array", 19 "[object Date]":"date", 20 "[object Error]":"error" 21 } 22 return _type[typeof o]||_type[_toString.call(o)]||(o?"object":"null"); 23 }