Several methods of judging object type in JavaScript

typeof method

typeof operator typeof is a unary operator that returns a string indicating the type of the operand.

 console.log( typeof {
    
    })
 console.log( typeof [])
 console.log( typeof new Date())

Output result:
insert image description here
Through the above simple example, we can find the defect of typeof, its ability is limited, and it returns "object" for Date and RegExp types.
So it is only useful when distinguishing between objects and primitive types. To distinguish one object type from another, other methods must be used.

instanceof method

The instanceof operator requires that its left operand is an object, and its right operand is the name of the object's class or a constructor. The instanceof operator returns true if object is an instance of a class or constructor. Returns false if object is not an instance of the specified class or function, or if object is null.

        let arr=[]
        let obj={
    
    }
        let date=new Date
        console.log(arr instanceof Array)
        console.log(arr instanceof Object)
        console.log(arr instanceof RegExp)
        console.log(obj instanceof Array)
        console.log(obj instanceof Object)
        console.log(obj instanceof RegExp)
        console.log(date instanceof Array)
        console.log(date instanceof Object)
        console.log(date instanceof Date)

Output result:
insert image description here

constructor property

In JavaScript, each object has a constructor attribute, which refers to the constructor that initializes the object, and is often used to determine the type of an unknown object. For example, given a known value, use the typeof operator to determine whether it is a primitive value or an object. If it is an object, you can use the constructor attribute to determine its type.
Write a simple example to determine whether an object is an array:

        let arr=[]
        console.log(arr.constructor == Array)

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43183219/article/details/124176591