Check if a value is an object in JavaScript

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

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

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 06:01

    Oh My God! I think this could be more shorter than ever, let see this:

    Short and Final code

    function isObject(obj)
    {
        return obj != null && obj.constructor.name === "Object"
    }
    
    console.log(isObject({})) // returns true
    console.log(isObject([])) // returns false
    console.log(isObject(null)) // returns false

    Explained

    Return Types

    typeof JavaScript objects (including null) returns "object"

    console.log(typeof null, typeof [], typeof {})

    Checking on Their constructors

    Checking on their constructor property returns function with their names.

    console.log(({}).constructor) // returns a function with name "Object"
    console.log(([]).constructor) // returns a function with name "Array"
    console.log((null).constructor) //throws an error because null does not actually have a property

    Introducing Function.name

    Function.name returns a readonly name of a function or "anonymous" for closures.

    console.log(({}).constructor.name) // returns "Object"
    console.log(([]).constructor.name) // returns "Array"
    console.log((null).constructor.name) //throws an error because null does not actually have a property

    Note: As of 2018, Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility

提交回复
热议问题