typeof 操作符

typeof用于返回以下原始类型

  • 基本类型:number/string/boolean
  • function
  • object
  • undefined

可以使用typeof用于判断数据的类型

  1. let foo = 10;
  2. let bar = 'hello';
  3. let baz = true;
  4. let qux;
  5. let fn = function () {};
  6. let obj = null;
  7. console.log(typeof foo); // number
  8. console.log(typeof bar); // string
  9. console.log(typeof baz); // boolean
  10. console.log(typeof qux); // undefined
  11. console.log(typeof fn); // function
  12. console.log(typeof obj); // object

instanceof 运算符

**instanceof**运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上,即检测引用类型。
也可以理解为是否为某个对象的实例,typeof 不能区分数组,但 instanceof 则可以。

  1. let fn = function () {};
  2. let obj = {};
  3. let arr = [1, 2, 3];
  4. console.log(fn instanceof Object); // true
  5. console.log(obj instanceof Object); // true
  6. console.log(arr instanceof Array); // true