总结:1. 一般简单的使用 typeof 或 instanceof 检测(这两种检测的不完全准确 2. 完全准确的使用 原生js中的 Object.prototype.toString.call 或 jquery中的 $.type 检测
1.使用typeof检测 number, string, boolean, function, undefined, json类型时,可以使用typeof进行判断。其他变量是判断不出类型的,包括null。 2. 使用instanceof检测 输出结果为boolean值。对于num, str和bool,不能检测出的类型,但是我们使用new,是可以检测出类型的.und和nul是检测的Object类型,才输出的true 3.使用constructor检测 在使用instanceof检测变量类型时,我们是检测不到number, ‘string’, bool的类型的。因此,我们需要换一种方式来解决这个问题。我们可以使用num.constructor==Number来判断num是不是Number类型的,其他的变量也类似。不过使用constructor也不是保险的,因为constructor属性是可以被修改的,会导致检测出的结果不正确。 4.使用Object.prototype.toString.call
console.log( Object.prototype.toString.call(num), Object.prototype.toString.call(str), Object.prototype.toString.call(bool), Object.prototype.toString.call(arr), Object.prototype.toString.call(json), Object.prototype.toString.call(func), Object.prototype.toString.call(und), Object.prototype.toString.call(nul), Object.prototype.toString.call(date), Object.prototype.toString.call(reg), Object.prototype.toString.call(error) ); // '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]' // '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'从输出的结果来看,Object.prototype.toString.call(变量)输出的是一个字符串,字符串里有一个数组,第一个参数是Object,第二个参数就是这个变量的类型,而且,所有变量的类型都检测出来了,我们只需要取出第二个参数即可。或者可以使用Object.prototype.toString.call(arr)=="object Array"来检测变量arr是不是数组。 5. jquery中$.type的实现
console.log( $.type(num), $.type(str), $.type(bool), $.type(arr), $.type(json), $.type(func), $.type(und), $.type(nul), $.type(date) $.type(reg), $.type(error) ); // number string boolean array object function undefined null date regexp error