Js data type detection in the actual development project process will often encounter, there are many pits, such as when we learn Js may only know to judge the data typeof a typeof is done, in fact, there is an instanceof, do you think these two kinds of enough? Can we determine exactly what each data type is? No, there are many pits waiting for you to jump, today we dig these pits out for everyone to see, together with the perfect pit avoidance!

1. Use Typeof detection

This is a type detection method that we often use. Let’s review it with a code:

typeof 1            // number
typeof '1'          // string
typeof undefined    // undefined
typeof true         // boolean
typeof Symbol(a)// symbol
typeof null         // object
typeof []           // object
typeof {}           // object
typeof console      // object
typeof console.log  // function
Copy the code

Typeof returns a reference type (object), which is not a reference type at all. This is a bug in Js itself. If the array type, object type, and reference type are returned as object, this is only true if the function type is used.

These pits should be avoided as far as possible in the actual development process!

2. Pass the Instanceof test

The instanceof method is used to determine whether the new object is an object generated by the previous constructor, and thus the data type of the new object. Let’s look at the code.

let Car = function() {}
let benz = new Car()
benz instanceof Car // true
let car = new String('Mercedes Benz')
car instanceof String // true
let str = 'Covid-19'
str instanceof String // false
Copy the code

So what’s the difference between Typeof and Instanceof?

  1. Instanceof can accurately determine complex reference data types, but not the underlying data types.

  2. Typeof also suffers from the fact that while it can determine the underlying data type (except null), it cannot determine any reference data type other than the function type.

In short, typeof and Instanceof alone are not sufficient for all scenarios, and can only be judged by mixing them. However, even using the two mixed writing method, it can only detect most cases, and it is also quite uncomfortable to write!

Therefore, in real development, the third judgment method is recommended!

3. Through the Object. The prototype. ToString detection

ToString () is an Object prototype method that returns uniformly a string of the format “[Object Xxx]”, where Xxx is the type of the Object. For Object objects, toString() returns [Object Object]; Other objects need to be called by call to return the correct type information. Let’s look at the code.

Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call({})  // Same result as above, add call also 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]"
Copy the code

This code can be seen from the above Object. The prototype. ToString. The call () is a good way to judge a reference type, it can even make a distinction between the document and the window.

Note that this method returns “[object Xxx]”, and the first letter of “Xxx” in the string must be capitalized (note: typeof returns lowercase).

So let’s implement a global general data type determination method to deepen understanding, the code is as follows.

function getType(obj){
  let type  = typeof obj;
  if(type ! = ="object") {    // Check typeof first, if it is a basic data type, return directly
    return type;
  }

  // If typeof returns object, regex returns result
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/.'$1');  // Note that there is a space between the re
}

/* Code validation, need to pay attention to case, which is typeof judgment, which is toString judgment? Think about the next * /
getType([])     // "Array" typeof [] is object, so toString is returned
getType('123')  // "string" typeof returns directly
getType(window) // "Window" toString returns
getType(null)   Typeof Null is object and toString is required
getType(undefined)   // "undefined" typeof returns directly
getType()            // "undefined" typeof returns directly
getType(function(){}) // "function" typeof can determine, so the first letter is lowercase
getType(/123/g)      / / "RegExp" toString returns
Copy the code

The above is the three methods of detecting data in Js, and finally realized a universal class detection method, which can basically handle the detection of all data types. Each method has its own strengths and weaknesses. In the process of use, we still need to see the specific choice of business scenarios!

Welcome everyone likes to pay attention to exchange, to recommend our open source excellent public account/small program mall system, welcome Star, use communication!

The open source project portal: github.crmeb.net/u/xingfu