typeof、instanceof的区别

65 阅读1分钟

typeof

返回一个字符串表示数据类型

  • typeof String(1) === "string"; // String 将任意值转换为字符串,比 toString 更安全
  • typeof Number(1) === "number"; // true Number 会尝试把参数解析成数值 typeof Number("shoe") === "number"; //true 包括不能将类型强制转换为数字的值
  • typeof null === "object"; //JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 null 代表的是空指针(大多数平台下值为 0x00),因此,null 的类型标签是 0,typeof null 也因此返回 "object"

instanceof

运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上


    function Car(make, model, year){
        this.make = make;
        this.model = model;
        this.model = model;
    }
    
   const Han = new Car('China','BYD','2024')
   
   console.log(Han instanceof Car)  //true
   console.log(Han instanceof Object)  //true

判断数组为空的方法

  1. Array.prototype.instanceOf(obj) && obj.length === 0
  2. JSON.stringify(arr) === '[]'
  3. Array.isArray()

判断对象为空:

  1. instanceOf 结合 Object.keys 方法 :Object.prototype.instanceOf(obj) && Object.keys(obj).length === 0
  2. Object.prototype.toString.call()
  3. instanceOf + for in + Object.hasOwnProperty
  4. JSON.stringify(item) === '{}'

非严格不等式

  • undefined == null //true
  • '' == [] == 0 //true