Check if a value is an object in JavaScript

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

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

30条回答
  •  失恋的感觉
    2020-11-22 05:40

    OK, let's give you this concept first before answering your question, in JavaScript Functions are Object, also null, Object, Arrays and even Date, so as you see there is not a simple way like typeof obj === 'object', so everything mentioned above will return true, but there are ways to check it with writing a function or using JavaScript frameworks, OK:

    Now, imagine you have this object that's a real object (not null or function or array):

    var obj = {obj1: 'obj1', obj2: 'obj2'};
    

    Pure JavaScript:

    //that's how it gets checked in angular framework
    function isObject(obj) {
      return obj !== null && typeof obj === 'object';
    }
    

    or

    //make sure the second object is capitalised 
    function isObject(obj) {
       return Object.prototype.toString.call(obj) === '[object Object]';
    }
    

    or

    function isObject(obj) {
        return obj.constructor.toString().indexOf("Object") > -1;
    }
    

    or

    function isObject(obj) {
        return obj instanceof Object;
    }
    

    You can simply use one of these functions as above in your code by calling them and it will return true if it's an object:

    isObject(obj);
    

    If you are using a JavaScript framework, they usually have prepared these kind of functions for you, these are few of them:

    jQuery:

     //It returns 'object' if real Object;
     jQuery.type(obj);
    

    Angular:

    angular.isObject(obj);
    

    Underscore and Lodash:

    //(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null)
    _.isObject(obj);
    

提交回复
热议问题