-3

After long times programming, I don't know why never have seen this:

var array = [];
array['one'] = 1;

console.log(array.length);

Here is a fiddle that shows array.length is zero (0):
https://jsfiddle.net/0c9v5txe/1/

Of-course, I don't need the length of array, just array.map is not working when the length is zero.

Isn't there really a way to force Javascript update the length of an associative array when adding a new item?

codeasaurus
  • 137
  • 7
Omid
  • 4,575
  • 9
  • 43
  • 74
  • length is equal to biggest numeric index + 1 – gawi May 28 '18 at 11:45
  • Indexing in the array is integer based. – Neeraj Wadhwa May 28 '18 at 11:45
  • The `length` returns the number of array elements, not the number of **any properties** of the object. What you did is you added an arbitrary property to the object, which of course is not treated as an array element. Try a numeric index instead. – Wiktor Zychla May 28 '18 at 11:46

2 Answers2

3

JavaScript doesn't have a feature called "associative arrays".

It has objects, and arrays are a type of object designed to hold numerically indexed values. (The length property on an array is calculated based on the highest numbered numerical property).

(Since arrays are a type of object, you can store arbitrary properties on them, but this is not a good practice).

If you want to store named properties, then do not use an array. Use a plain object or a Map. These serve the same purposes as associative arrays in other languages.

You can count the enumerated properties of an object by extracting them into an array and then checking its length.

var myObject = {};
myObject.one = 1;
console.log(Object.keys(myObject).length);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

you need to pass index, not value array[index] = value;

var array = [];
array[0] = "one";

console.log(array.length)
Akhil Aravind
  • 5,741
  • 16
  • 35