js 判断数据类型四种方法

鉴于 js 是松散类型的,因此需有一种手段来检测给定变量的数据类型。对此Js 也提供多种方法,但遗憾的是,不同的方法得到的结果参差不齐。

1、typeof

typeof 是一个操作符,其右侧跟一个一元表达式,并返回这个表达式的数据类型。返回的结果用该类型的字符串(全小写字母)形式表示,包括以下 7 种:number、boolean、symbol、string、object、undefined、function 等。

   typeof ''; // string 有效
   typeof 1; // number 有效
   typeof Symbol(); // symbol 有效
   typeof true; //boolean 有效
   typeof undefined; //undefined 有效
   typeof null; //object 无效
   typeof [] ; //object 无效
   typeof new Function(); // function 有效
   typeof new Date(); //object 无效
   typeof new RegExp(); //object 无效

2、instanceof

instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:instanceof 检测的是原型

   [] instanceof Array; // true
   {} instanceof Object;// true
   new Date() instanceof Date;// true
    
   function Person(){};
   new Person() instanceof Person;
    
   [] instanceof Object; // true
   new Date() instanceof Object;// true
   new Person instanceof Object;// true

3、constructor

对象的constructor属性用于返回创建该对象的函数

   var test=new Array();
   
   if (test.constructor==Array)
   {
   document.write("This is an Array");
   }
   if (test.constructor==Boolean)
   {
   document.write("This is a Boolean");
   }
   if (test.constructor==Date)
   {
   document.write("This is a Date");
   }
   if (test.constructor==String)
   {
   document.write("This is a String");
   }

细节问题:

  1. null 和 undefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。

  2. 函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object

4、toString

toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。

对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。

    Object.prototype.toString.call('') ;   // [object String]
    Object.prototype.toString.call(1) ;    // [object Number]
    Object.prototype.toString.call(true) ; // [object Boolean]
    Object.prototype.toString.call(Symbol()); //[object Symbol]
    Object.prototype.toString.call(undefined) ; // [object Undefined]
    Object.prototype.toString.call(null) ; // [object Null]
    Object.prototype.toString.call(new Function()) ; // [object Function]
    Object.prototype.toString.call(new Date()) ; // [object Date]
    Object.prototype.toString.call([]) ; // [object Array]
    Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
    Object.prototype.toString.call(new Error()) ; // [object Error]
    Object.prototype.toString.call(document) ; // [object HTMLDocument]
    Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用

方法:

export const typeExamine = (value: any) => {
  return Reflect.apply(Object.prototype.toString, value, [])
    .replace(/^\[object\s(\w+)\]$/, "$1")
    .toLowerCase();
};