1

I read that array can be as map, so why does it gives wrong result? Is there simple native way to use map in JavaScript and then get the length of it?

var f = [];
f["1_f_1"] = "1";
f["2_f_2"] = "2";
f["3_f_3"] = "3";

alert(f.length);

prints : 0

https://jsfiddle.net/fd6s1z0j/

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user63898
  • 29,839
  • 85
  • 272
  • 514

3 Answers3

5

JavaScript is not supported associative array so use object and get size by property name array size with the help of Object.keys() method.

// initialize as object
var f = {};

// define properties
f["1_f_1"] = "1";
f["2_f_2"] = "2";
f["3_f_3"] = "3";

// get object property name array and get length
alert(Object.keys(f).length);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Thanks , how do i get the first element for example ? f[0] doesn't work – user63898 Jul 25 '16 at 06:01
  • You can't get the element in the assigning order, since object doesn't have any certain order.... You can get element by `f[Object.keys(f)[0]]`. For getting it in certain order use array ... – Pranav C Balan Jul 25 '16 at 06:04
  • @user63898 : then `Object.keys(f).forEach(function(k){ console.log(f[k]); })` and with map `Object.keys(f).map(function(k){ return f[k]; })` – Pranav C Balan Jul 25 '16 at 06:06
  • @user63898 : with for loop `var keys = Object.keys(f); for(var i = 0 ; i < keys.length ; i++){ console.log(f[keys[i]]); }` – Pranav C Balan Jul 25 '16 at 06:09
2

An Array in JavaScript is just a special kind of an Object. If the keys of the Array object is a valid Array index (positive integer), only then it will be considered as an array element. Quoting the specification,

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253−1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232−1.

In your case, you are creating three new properties which are not valid array indexes. That is why they are not considered as the array elements, but just properties of the array object.

If you want to store those strings, then you should store them in an Object, like shown in the other answer.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

There are no associative arrays in JavaScript. Although, there are objects with named properties. What is often referred to as "associative array" is actually just an object in Javascript. If you want to get the length of element, you need to count all enumerable properties found directly upon object or simply use:-

Object.keys(obj).length
Vivek Pratap Singh
  • 9,326
  • 5
  • 21
  • 34