Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a string index in an array not increase the 'length'?

Tags:

javascript

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 = ""; 
like image 526
Dave Avatar asked Mar 02 '12 01:03

Dave


People also ask

What is the relationship between index of an array and size of an array?

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.

Do arrays have length property?

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.

Does length Return index?

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.

What is the function of the indexOf () in arrays?

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.


1 Answers

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' }; 
like image 73
deceze Avatar answered Sep 22 '22 22:09

deceze