1. Basic data type detection with typeof operator

1.1 Typeof operators

Yes, you heard that right,typeof is an operator, exactly a unary operator, not a method, not a method, not a method, say the important thing three times. The common use of typeof that we see is this

console.log(typeof('heihei')) // string
Copy the code

But you can actually use it this way

console.log(typeof 'heiheihei') // string
Copy the code

No surprise, no surprise,

Come on, brothers and sisters, tell me, what are the basic data types?

There are eight built-in types of JavaScript

  • A null value (null)
  • Undefined (undefined)
  • Boolean value (Boolean)
  • Number (number)
  • String (string)
  • Object (object)
  • Symbol (added in ES6)
  • BigInt (ES2020 introduced)

1.2 How to Use

console.log(typeof(1)); // "number" console.log(typeof("123")); // "string" console.log(typeof("true")); // "boolean" console.log(typeof(undefined)); // "undefined" console.log(typeof("null")); // "object" console.log(typeof({ a: 1 })); // "object" console.log(typeof Symbol()) ; // "Symbol" console.log(typeof (123n)); //"bigint" console.log(function a() {}); //"function"Copy the code

Some careful students may find that in addition to the 8 basic data types mentioned above, I also give an example of detecting function in the code. This is because function is also a kind of object, but it can be detected by Typeof, such as Array,Date,RegExp and other data Typeof does not make a good distinction, and why null is also detected as “object” will be discussed in the next article.

2. Reference data type detection using toString method

2.1 strong Object. The prototype. ToString

Typeof can only be used to detect basic data types and function types (again, there are only six basic data types, and function is one of the types of object). What about the other data types in object?

The answer is through the Object. The prototype. ToString this method, some students may be for this method is not very understand, in fact, simply is the method returns a “[Object” and the class “] “string. Class in this case means type.

Just look at the code.

console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(null)) // [object Null]
Copy the code

It’s easy to see how toString works, right, guys.

Through the Object. The prototype. ToString this method, we can at least identify the following such a variety of data types.

2.2 How to Use

Var number = 1; // [object Number] var string = '123'; // [object String] var boolean = true; // [object Boolean] var und = undefined; // [object Undefined] var nul = null; // [object Null] var obj = {a: 1} // [object Object] var array = [1, 2, 3]; // [object Array] var date = new Date(); // [object Date] var error = new Error(); // [object Error] var reg = /a/g; // [object RegExp] var func = function a(){}; // [object Function] function checkType() { for (var i = 0; i < arguments.length; i++) { console.log(Object.prototype.toString.call(arguments[i])) } } checkType(number, string, boolean, und, nul, obj, array, date, error, reg, func)Copy the code

In addition, there are Math and JSON data types that are not often detected

console.log(Object.prototype.toString.call(Math)); // [object Math]
console.log(Object.prototype.toString.call(JSON)); // [object JSON]
Copy the code

You can even detect Arguments

function a() {
    console.log(Object.prototype.toString.call(arguments)); // [object Arguments]
}
a();
Copy the code

Guys, this thing is not very powerful.

Return [object Number] [object String] [object Number]

We’ll give it a makeover and use this method to encapsulate a result that returns the number string of our family, and so on.

2.3 to the Object. The prototype. ToString ZhengZhengRong

Guys, before we wrap it, we need to understand what it means to wrap it. We’re wrapping it so that it doesn’t return something like [object Error], but something like Error.

With that in mind, let’s start to encapsulate this method.

3. Cosmetic procedures

3.1 Description

First of all, we need an object to hold the mapping between the two returns. For example, if I want to make [object Error] an Error, I don’t want them to correspond to each other.

Second, we need to put all the strings of the data types we want to check into the array.

Iterate through the array again, making the wrapped array element look like [object Number], and then turn it into the property value of the object, with the corresponding lowercase unwrapped array element Number becoming the property value of the object. So we’ve established the correspondence between these two.

3.2 Code Interpretation

const type = (obj) => { let typeList = {}; "Number Boolean String Null Undefined Array Function Object RegExp Date Error".split(" ") // 2. Map ((item) => {return (typeList[' [object ${item}] '] = item.tolowerCase ()); }); / / 3. Establish ` [object Number] ` and ` "Number" ` return mapping relations of these two kinds of results returned the typeof obj = = = "object" | | typeof obj = = = "function"? typeList[Object.prototype.toString.call(obj)] || "object"; }; // 4. If the reference type is already encapsulated, return the corresponding property value in the typeList. If the reference type is not encapsulated, put it directly back into object.Copy the code

At this point, a relatively complete type detection function can be used to detect reference types was born, of course, I am a novice, this is my personal words, do not say.

4. The typeof and Object. The prototype. The toString combination

Combine this function with the previous Typeof, using typeof for basic data types and toString for applied data types.

const type = (obj) => {
  let typeList = {};
  "Number Boolean String Null Undefined Array Function Object RegExp Date Error"
    .split(" ")
    .map((item) => {
      return (typeList[`[object ${item}]`] = item.toLowerCase());
    });
  if (typeof obj == "null") {
    return obj + "";
  }
  return typeof obj === "object" || typeof obj === "function"
    ? typeList[Object.prototype.toString.call(obj)] || "object"
    : typeof obj;
};
Copy the code

At this point, I think normal type checking should be ok with this function.

5. Expansion and extension

I’ll stop there, of course, but this is just the last post on type detection, because there are still some issues we haven’t addressed.

5.1 Remaining Problems

The first problem is that the above encapsulated method still has some types that cannot be detected, such as window,plainObject, etc., but these types are not common for new people like me, so I’ll stop there.

Second problem: the above two methods are mainly used to check the type of an object itself. If we want to determine whether an object is an instanceof another object, or if we want to determine whether an instance is an instanceof its parent or ancestor type, we use instanceof.

Plan after 5.2

In the next article, I’ll introduce the use of instanceof and then talk about how Typeof and Instanceof work.

Thank you for seeing this.

Also, this article is inspired by this article, the author’s other articles are also great, hope you have time to read.

Typing in JavaScript (part 1)