Length of a JavaScript object

前端 未结 30 3068
我在风中等你
我在风中等你 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:55

    Updated: If you're using Underscore.js (recommended, it's lightweight!), then you can just do

    _.size({one : 1, two : 2, three : 3});
    => 3
    

    If not, and you don't want to mess around with Object properties for whatever reason, and are already using jQuery, a plugin is equally accessible:

    $.assocArraySize = function(obj) {
        // http://stackoverflow.com/a/6700/11236
        var size = 0, key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) size++;
        }
        return size;
    };
    

提交回复
热议问题