Check if a value is an object in JavaScript

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

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

30条回答
  •  臣服心动
    2020-11-22 05:55

    Here's an answer with optional chaining, and perhaps the smallest isObj function for this question.

    const isObj = o => o?.constructor === Object;
    
    // True for this
    console.log(isObj({}));        // object!
    
    // False for these
    console.log(isObj(0));         // number
    console.log(isObj([]));        // array
    console.log(isObj('lol'));     // string
    console.log(isObj(null));      // null
    console.log(isObj(undefined)); // undefined
    console.log(isObj(() => {}));  // function
    console.log(isObj(Object));    // class

提交回复
热议问题