typeof
对检测 null、object、array 都是返回 object
console.log(typeof null); // objectconsole.log(typeof []); // objectconsole.log(typeof {}); // objectconsole.log(typeof new Number(1)); // object
instanceof
判断对象是否是指定构造函数的实例,无法判断原始值
console.log([] instanceof Array); // trueconsole.log({} instanceof Array); // trueconsole.log(function() {} instanceof Function); // trueconsole.log(1 instanceof Number); // falseconsole.log(new Number(1) instanceof Number); // true
toString
什么类型都可以,只是慢
function myTypeof(target) {var temp = {'[object Object]': 'object','[object Array]': 'array','[object Number]': 'obj-number','[object Boolean]': 'obj-boolean','[object String]': 'obj-string'}if(target === null) {return 'null';} else if(typeof target === 'object') {retrun temp[Object.prototype.toString.call(target)];} else {return typeof target;}}console.log(myTypeof(null)); // nullconsole.log(myTypeof(undefined)); // undefinedconsole.log(myTypeof(false)); // booleanconsole.log(myTypeof(1)); // numberconsole.log(myTypeof(new Number(1))); // obj-numberconsole.log(myTypeof(function() {})); // functionconsole.log(myTypeof([]); // arrayconsole.log(myTypeof({}); // object
Array.prototype.isArray
ES5 新增,检查是否为数组最快的方法
console.log(Array.isArray(null)); // falseconsole.log(Array.isArray(undefined)); // falseconsole.log(Array.isArray(false)); // falseconsole.log(Array.isArray(1)); // falseconsole.log(Array.isArray(new Number(1))); // falseconsole.log(Array.isArray(function() {})); // falseconsole.log(Array.isArray([]); // trueconsole.log(Array.isArray({}); // false
