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

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
So I am guessing that the value of length is calculated every time a new property is added to the object?
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.

4 Comments

array[1000000000] = "x" does not operate that way. Where is the limit?
Try var array; array = [ "a", "b", "c" ]; array[1000000000] = 1; array.length;
Add another 0 to the index and try again please.
@Amberlamps : This is the reason why : stackoverflow.com/questions/6154989/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.