Check if a value is an object in JavaScript

后端 未结 30 3855
臣服心动
臣服心动 2020-11-22 05:06

How do you check if a value is an object in JavaScript?

30条回答
  •  日久生厌
    2020-11-22 06:01

    var a = [1]
    typeof a //"object"
    a instanceof Object //true
    a instanceof Array //true
    
    var b ={a: 1}
    b instanceof Object //true
    b instanceof Array //false
    
    var c = null
    c instanceof Object //false
    c instanceof Array //false
    

    I was asked to provide more details. Most clean and understandable way of checking if our variable is an object is typeof myVar. It returns a string with a type (e.g. "object", "undefined").

    Unfortunately either Array and null also have a type object. To take only real objects there is a need to check inheritance chain using instanceof operator. It will eliminate null, but Array has Object in inheritance chain.

    So the solution is:

    if (myVar instanceof Object && !(myVar instanceof Array)) {
      // code for objects
    }
    

提交回复
热议问题