Anonymous Zombie
Anonymous Zombie

Reputation: 889

JavaScript Array.length returning 0

I have javascript Array that looks like enter image description here

The problem is Object.mappings has 3 elements which are clearly printed in console with console.log(), but when I try to find length of the array it returns 0. I tried stringifying the array and it just prints "[]".

what Am I doing wrong here?

Upvotes: 4

Views: 12283

Answers (3)

Konstantins Bogdanovs
Konstantins Bogdanovs

Reputation: 382

You can use length property only if array contains elements associated with indexes. If it is associative array then length property will return 0. You can count elements by yourself using this code:

function len(arr) {
  var count = 0;
  for (var k in arr) {
    if (arr.hasOwnProperty(k)) {
      count++;
    }
  }
  return count;
}

Then you can count elements of "mappings" array using len(mappings)

Upvotes: 5

Lewis
Lewis

Reputation: 14866

From this MDN article, the length property of an array represent an integer that's greater than the highest index in the array.

The length property represents an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

When you assigned non integer keys to array, the highest index is still 0.

var arr = [];
arr['abc'] = 1;
console.log(arr.length); //0
arr[100] = 2;
console.log(arr.length); //101

Upvotes: 3

Alxandr
Alxandr

Reputation: 12423

JavaScript arrays does not work like those in for instance PHP which can work as associative arrays. However, due to JavaScript's dynamic nature, and the fact that an Array is a subclass of Object, you can still attach arbitrary properties on to a Array. The length property will however not reflect this (as you have discovered).

If you're using newer browsers/polyfills (like core-js), I recommend going with Map instead (Documentation). Otherwise, use a simple object ({}), and use Object.keys on the object to get the keys.

Example of the later:

var mappings = {};
mappings['foo'] = 'bar';
Object.keys(mappings); // returns ['foo']
mappings[Object.keys(mappings)[0]]; // returns 'bar'

// Loop through all key-value pairs
Object.keys(mappings).forEach(function(key) {
  var value = mappings[key];
  // Do stuff with key and value.
});

Upvotes: 3

Related Questions