Length of Javascript Object (ie. Associative Array) *

Question

If I have a javascript associative array say:

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

Is there a built in or accepted best practice way to get the length of this array?

EDIT: JavaScript does not have associative arrays -- it only has objects, which can be used as a notion of associative arrays.

Answer

The most robust answer (i.e. 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.

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/5223/" >Length of Javascript Object (ie. Associative Array)< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment