判断js的类型的方法总结

109 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情

js的内置类型:

  • 基本类型:null undefined boolean number string Symbol bigint
  • 对象:Object

1. Object.prototype.toString.call("变量")

  • 常用获取一个变量的正确类型的方法
  • Object.prototype:Javascript中所有的对象都是Object的实例,并继承Object.prototype的属性和方法
  • .toString:可把一个逻辑值转换为字符串,并返回结果;这里用来返回一个表示该对象的字符串
  • .call:提供新的 this 值给当前调用的函数;这里用来将 this 指向要检测的值
Object.prototype.toString.call(null); // '[object Null]'
Object.prototype.toString.call(1); // '[object Number]'
Object.prototype.toString.call(""); // '[object String]'
Object.prototype.toString.call(undefined); // '[object Undefined]'
Object.prototype.toString.call(true); // '[object Boolean]'
Object.prototype.toString.call(Symbol()); // '[object Symbol]'
Object.prototype.toString.call(1n); // '[object BigInt]'

Object.prototype.toString.call([]); // '[object Array]'
Object.prototype.toString.call({}); // '[object Object]'
Object.prototype.toString.call(function () {}); // '[object Function]'
Object.prototype.toString.call(new RegExp()); // '[object RegExp]'
Object.prototype.toString.call(new Date()); // '[object Date]'
Object.prototype.toString.call(new Error()); // '[object Error]'
Object.prototype.toString.call(new Set()); // '[object Set]'
Object.prototype.toString.call(new Map()); // '[object Map]'

2. typeof

基本类型的判断:

  • 为什么typeof null打印出来为object: 因为在js最初的版本里,用的是32位系统,使用了低位存储了变量的类型信息;object的标签是000,而null代表的是空指针表示为全零,所以判断错误为object;不过我们可以通过null===null来进行判断
  • bigint:表示任意大的整数,可以用在一个整数字面量后面加 n 的方式定义一个 BigInt;
typeof null // object 
typeof undefined // undefined
typeof true // boolean
typeof NaN // number
typeof "" // undefined
typeof Symbol() // symbol
typeof 1n // bigint

对象的判断:

typeof [] // object 
typeof {} // object
typeof function () {} // function

3. instanceof

通过判断对象的原型链中是不是能找到指定类型的prorotype来判断对象的类型,返回true与false;

new Number() instanceof Number //true
[] instanceof Array //true
{} instanceof Object //true
function () {} instanceof Function //true

手动实现一个instanceof

  • 使用.__proto__获取创建该对象的构造函数的原型
  • 使用Reflect.getPrototypeOf()返回指定对象的原型;
function _instanceof(left, right) {
        if (typeof left !== "object" || left === null) return false;
        // 获取对象的原型
        let _left = left.__proto__;
        // let _left = Reflect.getPrototypeOf(left);
        // 获取类型的原型对象
        let _prototype = right.prototype;
        // 判断对象的类型是否等于类型的原型
        while (true) {
          if (_left === null) {
            return false;
          }
          if (_left === _prototype) {
            return true;
          }
          _left = _left.__proto__;
        }
      }
console.log(_instanceof([], Array));  //true
console.log(_instanceof({}, Object));  //true
console.log(_instanceof(2022, Date));  //false