1. 常用的typeof对于array、object、null的判断是不友好的,可以看下图的执行结果。var obj = { number:123, string: ‘123’, bool: true, obj: {}, arr: [], n: null, undef: undefined, fn: function () {}}for(key in obj) { console.log(key + “: " + typeof obj[key])}2. instanceofinstanceof测试构造函数的prototype属性是否出现在对象的原型链中的任何位置。如果你了解原型链,你会知道原型链的复杂性,instanceof得到的值并不是固定不变的,它会沿着原型链查找,最明显的是所有的基本数据类型都继承与Object.protype.[任何数据类型] instanceof Object> true如下图:3.最终方案:Object.prototype.toString.call()下面是兼容性方案最好、最全面、也是最有效的:下面有两种实现方式(原型方法和全局方法),可以根据自己的需要选择。(function () { function isType(type,data) { // data是全局方法时使用的,原型方法可不填 return Object.prototype.toString.call(data || this) === ‘[object ’ + type + ‘]’ } // 全局方法支持null和undefined // window.isType = isType // 添加到数据类型的原型中,不支持null和undefined Object.defineProperty(Object.prototype,‘isType’,{ value:isType, writable:true, enumerable:false, configurable:true });})()使用方式:var str = ‘abc’;// 全局方法isType(‘String’, str) // True// 原型方法str.isType(‘String’)测试代码:var obj = { test: { number:123, string: ‘123’, obj: {}, bool: true, arr: [], n: null, undef: undefined, fn: function () { } }}// 原型方法不支持null和undefined,请用“===”console.log(obj.test.number.isType(‘Number’))console.log(obj.test.number.isType(‘String’))console.log(obj.test.string.isType(‘String’))console.log(obj.test.string.isType(‘Number’))console.log(obj.test.obj.isType(‘Object’))console.log(obj.test.obj.isType(‘Array’))console.log(obj.test.arr.isType(‘Array’))console.log(obj.test.arr.isType(‘Object’))console.log(obj.test.fn.isType(‘Function’))console.log(obj.test.fn.isType(‘Object’))