Skip to content Skip to sidebar Skip to footer

Javascript Array.length Returning 0

I have javascript Array that looks like 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

Solution 1:

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:

functionlen(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)

Solution 2:

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 pairsObject.keys(mappings).forEach(function(key) {
  var value = mappings[key];
  // Do stuff with key and value.
});

Solution 3:

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

Post a Comment for "Javascript Array.length Returning 0"