Check if a value is an object in JavaScript

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

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

30条回答
  •  春和景丽
    2020-11-22 05:45

    It is an old question but thought to leave this here. Most people are checking if the variable is {} meaning a key-value paired and not what is the underline construct that JavaScript is using for a given thing, cuz to be honest mostly everything in JavaScript is an object. So taking that out of the way. If you do...

    let x = function() {}
    typeof x === 'function' //true
    x === Object(x) // true
    x = []
    x === Object(x) // true
    
    // also
    x = null
    typeof null // 'object'
    

    Most of the time what we want is to know if we have a resource object from an API or our database call returned from the ORM. We can then test if is not an Array, is not null, is not typeof 'function', and is an Object

    // To account also for new Date() as @toddmo pointed out
    
    x instanceof Object && x.constructor === Object
    
    x = 'test' // false
    x = 3 // false
    x = 45.6 // false
    x = undefiend // false
    x = 'undefiend' // false
    x = null // false
    x = function(){} // false
    x = [1, 2] // false
    x = new Date() // false
    x = {} // true
    

提交回复
热议问题