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 = {}?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With