typeof

对检测 null、object、array 都是返回 object

  1. console.log(typeof null); // object
  2. console.log(typeof []); // object
  3. console.log(typeof {}); // object
  4. console.log(typeof new Number(1)); // object

instanceof

判断对象是否是指定构造函数的实例,无法判断原始值

  1. console.log([] instanceof Array); // true
  2. console.log({} instanceof Array); // true
  3. console.log(function() {} instanceof Function); // true
  4. console.log(1 instanceof Number); // false
  5. console.log(new Number(1) instanceof Number); // true

toString

什么类型都可以,只是慢

  1. function myTypeof(target) {
  2. var temp = {
  3. '[object Object]': 'object',
  4. '[object Array]': 'array',
  5. '[object Number]': 'obj-number',
  6. '[object Boolean]': 'obj-boolean',
  7. '[object String]': 'obj-string'
  8. }
  9. if(target === null) {
  10. return 'null';
  11. } else if(typeof target === 'object') {
  12. retrun temp[Object.prototype.toString.call(target)];
  13. } else {
  14. return typeof target;
  15. }
  16. }
  17. console.log(myTypeof(null)); // null
  18. console.log(myTypeof(undefined)); // undefined
  19. console.log(myTypeof(false)); // boolean
  20. console.log(myTypeof(1)); // number
  21. console.log(myTypeof(new Number(1))); // obj-number
  22. console.log(myTypeof(function() {})); // function
  23. console.log(myTypeof([]); // array
  24. console.log(myTypeof({}); // object

Array.prototype.isArray

ES5 新增,检查是否为数组最快的方法

  1. console.log(Array.isArray(null)); // false
  2. console.log(Array.isArray(undefined)); // false
  3. console.log(Array.isArray(false)); // false
  4. console.log(Array.isArray(1)); // false
  5. console.log(Array.isArray(new Number(1))); // false
  6. console.log(Array.isArray(function() {})); // false
  7. console.log(Array.isArray([]); // true
  8. console.log(Array.isArray({}); // false