typeof
对检测 null、object、array 都是返回 object
console.log(typeof null); // object
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof new Number(1)); // object
instanceof
判断对象是否是指定构造函数的实例,无法判断原始值
console.log([] instanceof Array); // true
console.log({} instanceof Array); // true
console.log(function() {} instanceof Function); // true
console.log(1 instanceof Number); // false
console.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)); // null
console.log(myTypeof(undefined)); // undefined
console.log(myTypeof(false)); // boolean
console.log(myTypeof(1)); // number
console.log(myTypeof(new Number(1))); // obj-number
console.log(myTypeof(function() {})); // function
console.log(myTypeof([]); // array
console.log(myTypeof({}); // object
Array.prototype.isArray
ES5 新增,检查是否为数组最快的方法
console.log(Array.isArray(null)); // false
console.log(Array.isArray(undefined)); // false
console.log(Array.isArray(false)); // false
console.log(Array.isArray(1)); // false
console.log(Array.isArray(new Number(1))); // false
console.log(Array.isArray(function() {})); // false
console.log(Array.isArray([]); // true
console.log(Array.isArray({}); // false