js数据类型判断
Object.prototype.toString.call(data)
var bool = true var num = 1 var str = 'abc' var und = undefined var nul = null var arr = [1,2,3] var obj = {name:'haoxl',age:18} var fun = function(){console.log('I am a function')} console.log(Object.prototype.toString.call(bool));//[object Boolean] console.log(Object.prototype.toString.call(num));//[object Number] console.log(Object.prototype.toString.call(str));//[object String] console.log(Object.prototype.toString.call(und));//[object Undefined] console.log(Object.prototype.toString.call(nul));//[object Null] console.log(Object.prototype.toString.call(arr));//[object Array] console.log(Object.prototype.toString.call(obj));//[object Object] console.log(Object.prototype.toString.call(fun));//[object Function] function Person(){} function Student(){} Student.prototype = new Person() var haoxl = new Student() console.log(Object.prototype.toString.call(haoxl));//[object Object] //原理(摘自高级程序设计3):在任何值上调用 Object 原生的 toString() 方法,都会返回一个 [object NativeConstructorName] 格式的字符串。每个类在内部都有一个 [[Class]] 属性,这个属性中就指定了上述字符串中的构造函数名。 //但是它不能检测非原生构造函数的构造函数名。
使用jquery中的$.type
console.log($.type(bool));//boolean console.log($.type(num));//number console.log($.type(str));//string console.log($.type(und));//undefined console.log($.type(nul));//null console.log($.type(arr));//array console.log($.type(obj));//object console.log($.type(fun));//function function Person(){} function Student(){} Student.prototype = new Person() var haoxl = new Student() console.log($.type(haoxl));//object // $.type()内部原理就是用的Object.prototype.toString.call()