In the example below, the array2.length
is only 10
, while in my mind, it should be 13
.
Why does the "string keyed" indexes not increase the length
of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length
not increased?
var array2 = new Array(); array2["a"] = new Array(); array2["b"] = new Array(); array2["c"] = new Array(); for (var i = 0; i < 10; ++i) array2[i] = new Array(); var nothing = ""; for (var i = 0; i < array2.length; ++i) nothing = "";
For example n = 10 means there are 10 elements in the array ( persons in this case ). So the size of array is 10. Person[0] represents the first element in the array. This is called indexing, as we are using an index number to address an element.
length is a property of arrays in JavaScript that returns or sets the number of elements in a given array. The length property of an array can be returned like so. The assignment operator, in conjunction with the length property, can be used to set the number of elements in an array like so.
The length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index of the array. The length returns the number of elements that a dense array has.
indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Javascript arrays cannot have "string indexes". A Javascript Array
is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo'; array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {}; obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array
:
// numerically indexed Array var array = ['foo', 'bar', 'baz']; // associative Object var dict = { foo : 42, bar : 'baz' };
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