Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy array behaviour?

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 = {}?

like image 258
Amberlamps Avatar asked Aug 23 '12 12:08

Amberlamps


2 Answers

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.

like image 174
nnnnnn Avatar answered Nov 19 '22 06:11

nnnnnn


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.

like image 24
Clyde Lobo Avatar answered Nov 19 '22 07:11

Clyde Lobo