Length of a JavaScript object

If I have a JavaScript object, say

var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

is there a built-in or accepted best practice way to get the length of this object?


The most robust answer (ie that captures the intent of what you're trying to do while causing the fewest bugs) would be:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an object
var size = Object.size(myArray);

There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.


Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

var size = Object.keys(myObj).length;

This doesn't have to modify any existing prototype since Object.keys() is now built in.


如果你知道你不必担心hasOwnProperty检查,你可以很简单地做到这一点:

Object.keys(myArray).length

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;
};
链接地址: http://www.djcxy.com/p/704.html

上一篇: 如何检查一个对象是否在JavaScript中有属性?

下一篇: JavaScript对象的长度