JavaScript数据类型检测代码分享
/**
*param:o表示检测的值
*return:返回字符串"undefined"、"number"、"boolean"、"string"、"function"、"regexp"、"array"、"date"、"error"、"object"或"null"
*/
functiontypeOf(o){
var_toString=Object.prototype.toString; //获取对象的toString()方法引用
//列举基本数据类型和内置对象类型,你还可以进一步补充该数组的检测数据类型范围
var_type={
"undefined":"undefined",
"number":"number",
"boolean":"boolean",
"string":"string",
"[objectFunction]":"function",
"[objectRegExp]":"regexp",
"[objectArray]":"array",
"[objectDate]":"date",
"[objectError]":"error"
}
return_type[typeofo]||_type[_toString.call(o)]||(o?"object":"null");//通过把值转换为字符串,然后匹配返回字符串中是否包含特定字符进行检测
}
//应用示例:
vara=Math.abs;
alert(typeOf(a)); //返回字符串"function"
代码很简单,说明都在注释里,这里就不多废话了,有相同需求的小伙伴自己来参考下吧