Length of a JavaScript object

前端 未结 30 3097
我在风中等你
我在风中等你 2020-11-21 04:35

I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?

const myObject = new Object();
myObject["         


        
30条回答
  •  耶瑟儿~
    2020-11-21 04:54

    To not mess with the prototype or other code, you could build and extend your own object:

    function Hash(){
        var length=0;
        this.add = function(key, val){
             if(this[key] == undefined)
             {
               length++;
             }
             this[key]=val;
        }; 
        this.length = function(){
            return length;
        };
    }
    
    myArray = new Hash();
    myArray.add("lastname", "Simpson");
    myArray.add("age", 21);
    alert(myArray.length()); // will alert 2
    

    If you always use the add method, the length property will be correct. If you're worried that you or others forget about using it, you could add the property counter which the others have posted to the length method, too.

    Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)

提交回复
热议问题