Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array length issue [duplicate]

I'm a bit lost with the following:

When I do a console.log of two different arrays, one is giving me the actual length but not the other.

Output of first array, with good length:

[Object, Object, Object]
  0: Object
  1: Object
  2: Object
  length: 3
  __proto__: Array[0]

Output of the second one, length should be 4 but is actually 0:

[A: Object, B: Object, C: Object, D: Object]
  A: Object
  B: Object
  C: Object
  D: Object
  length: 0
  __proto__: Array[0]

Why do my first array do have a correct length, but not the second one ?

Edit: this is the code generating the above output:

var links = [
  {source: "A", target: "B"},
  {source: "A", target: "C"},
  {source: "A", target: "D"}
];

var nodes = [];

// Compute the distinct nodes from the links.
links.forEach(function(link) {
  link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
  link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});

console.log(links);
console.log(nodes);
like image 894
Pierre Avatar asked Jan 17 '26 22:01

Pierre


2 Answers

The second log message cannot output the length of the array because the values have been assigned to its properties as opposed to its indices, since there are no objects within the actual indices of the array the length property is 0. This occurs because arrays cannot contain non-numeric indices such as A,B,C,D.

So when you execute:

var arr= [];
arr["b"] = "test";

The code is actually assigning the string literal test to the b property of the arr array as opposed to an index. This is possible because arrays are objects in Javascript, so they may also have properties.

like image 99
Kevin Bowersox Avatar answered Jan 20 '26 10:01

Kevin Bowersox


The length of an Array object is simply its highest numeric index plus one. The second object has no numeric indices, so its length is 0.

If it were [ A: Object, B: Object, C: Object, 15: Object ], then its length would be 16. The value of length is not tied to the number of actual properties (4 in this case).

like image 40
Mark Reed Avatar answered Jan 20 '26 10:01

Mark Reed