2

Is it possible to get length of an array without iterating complete array having non numeric indexes?

Length property is always 0 for non numeric indexed array.

Can we get number of elements using another property of array or it's prototype?

var arr = [];
arr['first'] = 1;
arr['second'] = 2;
console.log(arr.length); //0
P K
  • 9,972
  • 12
  • 53
  • 99
  • 1
    It's not an array, it's just an object with properties. arr['first'] is the same as arr.first. Also a dupe of this question, which can help you: http://stackoverflow.com/questions/5223/length-of-javascript-associative-array – bhamlin Mar 12 '12 at 18:45

2 Answers2

6

Arrays are meant for numeric indices.

You can add other properties, but they have no impact on the length, and the methods of Array.prototype will ignore them.

If you're using non-numeric properties, you should be using {} (an Object), and you'll need to maintain your own .length.

Alternately, you could use the Object.keys method to find out how many properties there are...

var obj = {};
obj['first'] = 1;
obj['second'] = 2;

var n = Object.keys(obj).length; // 2

For browsers that don't support ECMAScript 5, you'll need a compatibility patch...

0

Okay so the problem is you are not adding values to the array, you're adding properties to the object. As far as getting the number of native properties for an object you can use the Object.keys(arr).length

Nimnam1
  • 515
  • 4
  • 12