一、使用 typeof
typeof 返回对数的类型
typeof 123 == 'number'
typeof '123' == 'string'
typeof [1,2,3] == 'object'
typeof {a:1} == 'object'
typeof null == 'object'
typeof function(){} == 'function'
typeof true == 'boolean'
typeof undefined = 'undefined'
结论:typeof 不能用来判断数据是 数组、对象 或者是 null
二、使用 instanceof
暂且不谈
三、使用 Object.prototype.toString.call()
Object.prototype.toString.call(123) == '[object Number]'
Object.prototype.toString.call('123') == '[object String]'
Object.prototype.toString.call(true) == '[object Boolean]'
Object.prototype.toString.call(function(){}) == '[object Function]'
Object.prototype.toString.call([1,2,3]) == '[object Array]'
Object.prototype.toString.call({a:1}) == '[object Object]'
Object.prototype.toString.call(null) == '[object Null]'
Object.prototype.toString.call(undefined) == '[object Undefined]'
所以,该用那个呢 ? 不需要在说了吧。
所以,该用 Object.prototype.toString.call() ............
var data = '' // 一个你需要验证的数据
Object.prototype.toString.call(data).slice(8,this.length-1) // 返回的值,就是 data 的数据类型
Object.prototype.toString.call 原理 ? ? ?
// 如下
Object.toString === Object.prototype.toString // false
Object.prototype.toString() // "[object Object]"
Object.toString() // "function Object() { [native code] }"