LENGTH OF JAVASCRIPT OBJECT (IE. ASSOCIATIVE ARRAY)

Tanuj Kumar

Total Post:134

Points:940
Posted by  Tanuj Kumar
 1543  View(s)
Ratings:
Rate this:

Hi!

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.

Please help me!

Thanks in advance!

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Length of Javascript Object (ie. Associative Array)

    Hi Tanuj!

    Get the length of JavaScript Object, try this way

    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);

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!