A general method for judging data types in Js

typeofBoth instanceofare methods for judging data types, the differences are as follows:

  • typeofWill return the basic type of a variable, instanceofand return a boolean value

  • instanceof Can accurately judge complex reference data types, but cannot correctly judge basic data types

  • And  typeof there are also disadvantages. Although it can judge the basic data type ( null except), but the reference data type, except  function for the type, other can not judge

It can be seen that the above two methods have disadvantages and cannot meet the needs of all scenarios

If you need a general detection data type, you can use it Object.prototype.toString, call this method, and return “[object Xxx]” a string in a uniform format

as follows:

Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call({})  // 同上结果,加上call也ok
Object.prototype.toString.call(1)    // "[object Number]"
Object.prototype.toString.call('1')  // "[object String]"
Object.prototype.toString.call(true)  // "[object Boolean]"
Object.prototype.toString.call(function(){})  // "[object Function]"
Object.prototype.toString.call(null)   //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g)    //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([])       //"[object Array]"
Object.prototype.toString.call(document)  //"[object HTMLDocument]"
Object.prototype.toString.call(window)   //"[object Window]"

After understanding toStringthe basic usage of , let's implement a global and general data type judgment method:

function getType(obj){
  let type  = typeof obj;
  if (type !== "object") {    // 先进行typeof判断,如果是基础数据类型,直接返回
    return type;
  }
  // 对于typeof返回结果是object的,再进行如下的判断,正则返回结果
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1').toLowerCase(); 
}

Use as follows:

getType([])     // "array" typeof []是object,因此toString返回
getType('123')  // "string" typeof 直接返回
getType(window) // "window" toString返回
getType(null)   // "null",typeof null是object,需toString来判断
getType(undefined)   // "undefined" typeof 直接返回
getType()            // "undefined" typeof 直接返回
getType(function(){}) // "function" typeof 能判断
getType(/123/g)      //"regExp" toString返回

Guess you like

Origin blog.csdn.net/weixin_45346457/article/details/125709544