javascript - check if object is empty

前端 未结 5 1083
感情败类
感情败类 2021-02-05 08:57

I am trying to create to javascript/jquery test to check if my object is empty and cannot figure it out.

Here is the object when it has something in it:

         


        
5条回答
  •  自闭症患者
    2021-02-05 09:29

    Alternatively, you can write the isEmpty function on the Object prototype.

    Object.prototype.isEmpty = function() {
        for(var key in this) {
            if(this.hasOwnProperty(key))
                return false;
        }
        return true;
    }
    

    Then you can easily check if the object is empty like so.

    var myObj = {
        myKey: "Some Value"
    }
    
    if(myObj.isEmpty()) {
        // Object is empty
    } else {
        // Object is NOT empty (would return false in this example)
    }
    

    Source solution: https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty

提交回复
热议问题