Check if a value is an object in JavaScript

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

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

30条回答
  •  梦如初夏
    2020-11-22 05:43

    I'm fond of simply:

    function isObject (item) {
      return (typeof item === "object" && !Array.isArray(item) && item !== null);
    }
    

    If the item is a JS object, and it's not a JS array, and it's not null…if all three prove true, return true. If any of the three conditions fails, the && test will short-circuit and false will be returned. The null test can be omitted if desired (depending on how you use null).

    DOCS:

    http://devdocs.io/javascript/operators/typeof

    http://devdocs.io/javascript/global_objects/object

    http://devdocs.io/javascript/global_objects/array/isarray

    http://devdocs.io/javascript/global_objects/null

提交回复
热议问题