Check if a value is an object in JavaScript

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

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

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 06:02

    Little late... for "plain objects" (i mean, like {'x': 5, 'y': 7}) i have this little snippet:

    function isPlainObject(o) {
       return (o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ) ?
               false
              :(typeof o == 'object');
    }
    

    It generates the next output:

    console.debug(isPlainObject(isPlainObject)); //function, false
    console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
    console.debug(isPlainObject(5)); //number, false
    console.debug(isPlainObject(undefined)); //undefined, false
    console.debug(isPlainObject(null)); //null, false
    console.debug(isPlainObject('a')); //string, false
    console.debug(isPlainObject([])); //array?, false
    console.debug(isPlainObject(true)); //bool, false
    console.debug(isPlainObject(false)); //bool, false
    

    It always works for me. If will return "true" only if the type of "o" is "object", but no null, or array, or function. :)

提交回复
热议问题