Javascript common data type judgment method

Javascript common data type judgment method

There are five common types of judgment methods in Javascript:

  • typeof operator
  • === strict equality operator
  • instanceof operator
  • constructor property
  • Object.prototype.toString.call()

Below I will give a brief introduction to Javascript data types, and then analyze and discuss the five types of judgment methods.

1. Javascript data types

First of all, you need to know that Javascript is a dynamically typed language, so you don't need to specify the type when defining variables, which means that the same variable may belong to different types at different times.
This article only expands on the data types and does not explain them in detail. You can refer to the JavaScript data types on the MDN official website .

1.1 Primitive data types

  • Number numeric type
  • String character type
  • Boolean Boolean type
  • Undefined type
  • Null type
  • Symbol symbol type (ES6 new)
  • Bigint type (new in ES6)

1.2 Reference data types

The reference data type can be summarized as the Object object type, but in fact Object can be subdivided into many subclasses, the following 8 common ones.

  • Array array type
  • Function function type
  • Error error type
  • Date date type
  • RegExp regular type
  • Set, WeakSet types (ES6 new)
  • Map, WeakMap types (ES6 new)
  • Promise object (new in ES6)

2. Method 1: typeof A

//原始类型:除 Null 之外, typeof值都是对应的类型
console.log(typeof 2); // number
console.log(typeof "str"); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof Symbol(1)); // symbol
console.log(typeof BigInt(1)); // bigint

// 引用类型:除了 Function 对象实例, typeof值都是 object
console.log(typeof new Object()); // object
console.log(typeof new Array()); // object
console.log(typeof new Function()); // function
console.log(typeof new Error("err")); // object
console.log(typeof new RegExp()); // object
console.log(typeof new Date()); // object
console.log(typeof new Set()); // object
console.log(typeof new Map()); // object
console.log(typeof new Promise((resolve, reject) => resolve("data"))); // object

2.1 Typeof Notes

  1. The null type returns object (historical problems, see reference blog 1 for details )
  2. Function type returns function

2.2 Summary of typeof method

The typeof method can be seen from the above running results:

  • For primitive data types: Except for Null, other type judgments are accurate.
  • For reference data types: In addition to Function, other Object subtypes need to use other judgment methods to distinguish types.

3. Method 2: A === B

let myNull = null;
console.log(myNull === null); // true
let myUndefined;
console.log(myUndefined === undefined); // true

3.1 === method summary

  • === The type judgment ability of the method is weak
  • It can only be used to judge null and undefined types, and is used to make up for the shortcoming of typeof null = object.

4. Method 3: object instanceof constructor

The instanceof operator is used to detect whether the prototype property of the constructor appears on the prototype chain of an instance object.

// 数据类型无法检测
console.log(2 instanceof Number); // false
console.log(true instanceof Boolean); // false
console.log("str" instanceof String); // false
let myUndefined;
console.log(undefined instanceof undefined); // TypeError
let myNull = null;
console.log(myNull instanceof null); // TypeError
console.log(Symbol(1) instanceof Symbol); // false
console.log(1n instanceof BigInt); // false

// 可以检测内置对象类型
console.log({
    
    } instanceof Object); // true
console.log([] instanceof Array); // true
console.log(function () {
    
    } instanceof Function); // true
console.log(new Error("err") instanceof Error); // true
console.log(/1/ instanceof RegExp); // true
console.log(new Date() instanceof Date); // true
console.log(new Set() instanceof Set); // true
console.log(new Map() instanceof Map); // true
console.log(
  new Promise((resolve, reject) => resolve("data")) instanceof Promise
); // true

But instanceof can only judge whether two objects belong to the instance relationship, so it has the disadvantage of inaccurate judgment.
Such as the following code:

function myFun() {
    
    }
console.log(myFun instanceof Object); // true
console.log(myFun instanceof Function); // true
// new myFun() 是 myFun 的一个实例
console.log(new myFun() instanceof foo); // true
console.log(new myFun() instanceof Object); // true
console.log(new myFun() instanceof Function); // true

4.1 Summary of instanceof method

It can be seen from the above running results that the instanceof method has the following disadvantages:

  1. instanceof cannot determine primitive data types. (null and undefined cannot be used, and an error will be reported)
  2. instanceof can judge the reference data type, but due to the existence of the prototype chain, it cannot judge the data type very accurately.

5. Method 4: A.constructor === B

Before using the constructor method, you must have the concept of a prototype object triangle diagram :

  • Each object has a __proto__ attribute, which points to its own prototype object
  • Each constructor has a prototype property, which points to the prototype object of the instance object
  • The constructor in the prototype object points to the constructor itself

As shown below:

So when an instance object accesses the constructor attribute, since it does not have this attribute, it will follow the prototype chain to access the constructor attribute of its prototype object.

// 原始数据类型
console.log((2).constructor === Number); // true
console.log("str".constructor === String); // true
console.log(true.constructor === Boolean); // true
//由于 null 和 undefined 没有构造函数
console.log(undefined.constructor); // TypeError
console.log(null.constructor); // TypeError
console.log(Symbol(1).constructor === Symbol); // true
console.log(2n.constructor === BigInt); // true

//引用数据类型
console.log({
    
    }.constructor === Object); // true
console.log([].constructor === Array); // true
console.log(function () {
    
    }.constructor === Function); // true
console.log(new Error("err").constructor === Error); // true
console.log(/1/.constructor === RegExp); // true
console.log(new Date().constructor === Date); // true
console.log(new Set().constructor === Set); // true
console.log(new Map().constructor === Map); // true
console.log(
  new Promise((resolve, reject) => resolve("data")).constructor === Promise
); // true

However, if the prototype of the constructor is modified before the object is created, the constructor method will be unreliable.
The following code:

function myFun() {
    
    }
Object.setPrototypeOf(myFun, Array.prototype);
console.log(myFun.constructor === Function); // false
console.log(myFun.constructor === Array); // true

5.1 Summary of constructor methods

From the above running results, it can be seen that the constructor method has the following disadvantages:

  1. In the original data type, null and undefined have no constructor, so there is no prototype chain, and the constructor method cannot be used. These two types need to be judged by other methods.
  2. The constructor method is unstable. When the prototype of the object is rewritten, the original constructor reference will be changed. (default is Object)

6. Method five: Object.prototype.toString.call()

Each object has a toString () method, by default, the toString () method is inherited by each Object object. If this method is not overridden in a custom object, toString() returns "[object type]". (type is the type of object)

//原始数据类型
console.log(Object.prototype.toString.call(123)); //[object Number]
console.log(Object.prototype.toString.call("123")); //[object String]
console.log(Object.prototype.toString.call(true)); //[object Boolean]
console.log(Object.prototype.toString.call(undefined)); //[object Undefined]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call(undefined)); //[object Undefined]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call(Symbol(1))); //[object Symbol]
console.log(Object.prototype.toString.call(2n)); //[object BigInt]

//引用数据类型
console.log(Object.prototype.toString.call({
    
    })); //[object Object]
console.log(Object.prototype.toString.call([])); //[object Array]
console.log(Object.prototype.toString.call(function () {
    
    })); //[object Function]
console.log(Object.prototype.toString.call(new Error("err"))); //[object Error]
console.log(Object.prototype.toString.call(/1/)); // [object RegExp]
console.log(Object.prototype.toString.call(new Date())); // [object Date]
console.log(Object.prototype.toString.call(new Set())); // [object Set]
console.log(Object.prototype.toString.call(new Map())); // [object Map]
console.log(
  Object.prototype.toString.call(
    new Promise((resolve, reject) => resolve("data"))
  )
); //[object Promise]

Because the Object.prototype.toString.call() method is cumbersome to call, and the return result is not easy to judge.
So we can simply encapsulate this method to facilitate subsequent calls.

let getType = (target) => Object.prototype.toString.call(target).slice(8, -1);
getType({
    
    }); //Object
getType([]); //Array

6.1 Summary of Object.prototype.toString.call() method

It can be seen from the above running results:

  • The Object.prototype.toString.call() method can accurately judge all data types. We only need to simply encapsulate it to get a type judgment method that is easy to call and returns a clear result.

In addition, we can also use the API packaged by the third-party library to perform type judgment, such as the type API in Jquery .

7. Summary of the full text

  • The typeof method can determine the original data type except null.
  • The === method can only be used to judge null and undefined.
  • The instanceOf and constructor methods involve the prototype chain. Because the prototype chain of the custom object can be changed, these two methods are not stable.
  • The Object.prototype.toString.call() method is the best way to determine the data type.

With the knowledge of data type judgment, we can try to write the deep and shallow copy function by hand. Next, I will update and implement the deep and shallow copy function .

Reference blog:

Code words are not easy, friends who find it helpful will like it, and follow it.

If you have doubts about this article, you can discuss it in the comment area. Everyone is welcome to point out the wrong views in the text.

Guess you like

Origin blog.csdn.net/forward_xx/article/details/126915060