8

I know that an array in JavaScript is nothing else than an object. When I define an array like that:

var array;
array = [ "a", "b", "c" ];

and run

Object.keys(array);

I get following array: ["0", "1", "2"]. Array length of array is 3.

When I add a property like:

array["a"] = "d";

Object.keys() is returning ["0", "1", "2", "a"], but array length of array is still 3.

But when I add a property like that:

array["3"] = "d";

the length of array is now 4.

If array is just another object, how can I achieve that kind of behaviour when I start my object from scratch like var myArray = {}?

Amberlamps
  • 39,180
  • 5
  • 43
  • 53
  • 6
    [Read this classic blog post from Kangax](http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/) - it turns out that you cannot do what you're asking. – Pointy Aug 23 '12 at 12:29
  • possible duplicate of [Javascript array length incorrect on array of objects](http://stackoverflow.com/questions/2528680/javascript-array-length-incorrect-on-array-of-objects) – epascarello Aug 23 '12 at 12:29

2 Answers2

1

The .length property only includes properties with numeric indices, specifically those with integer values greater than or equal to zero.

If you're asking how to get a total count of all keys from an array or an object then you could do:

Object.keys(array).length

...since Object.keys() returns an array that will itself have a .length property.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • P.S. Note that `.length` could actually be _greater_ than `Object.keys(array).length` because (as pointed out by Clyde) the length is one greater than the highest integer index, but JS allows sparse arrays and `Object.keys()` only returns indexes that have actually been assigned. – nnnnnn Aug 23 '12 at 13:08
  • So I am guessing that the value of `length` is calculated every time a new property is added to the object? – Amberlamps Aug 23 '12 at 13:10
1

The length property of array is the value of the highest numerical index + 1.

So after array["3"] = "d"; the highest numeric index is 3 hence the length returns 4

Object.keys(array).length should give you the length.

Clyde Lobo
  • 9,126
  • 7
  • 34
  • 61