How can I get the real amount of an array?

I tried this way, but it returns me the wrong score:

myArr = []; myArr[666] = 'hello there'; console.log(myArr.length); // returns me 667 

It should be 1. How can I get a good score in the fastest way?

+6
source share
4 answers

It should be 1.

No, it should be 667, because the way length defined for standard arrays in JavaScript that are not arrays at all . Arrays in JavaScript are inherently sparse, that is, they can have holes in them (indexes where no value is stored).

How can I get a good score in the fastest way?

The only way is a loop. For instance:

 var count = 0; myArr.forEach(function() { ++count; }); console.log(count); 

... or through reduce , as in maček answer . forEach , reduce and other similar only entries that actually exist, so they skip holes in sparse arrays.


I should mention that since IE8 still (sigh) has a fair market share, you need to color forEach and reduce and such on it if you want to use them. (This is easy.)

To do this without any shimming and only read the actual properties of the index (not other kinds of properties), then freely:

 var count = 0, name; for (name in myArr) { if (myArr.hasOwnProperty(name) && /^[0-9]+$/.test(name)) { ++count; } } 

This uses a slightly loose definition of what an index property name is; if you want reliable, see the "Use in-in correctly" section of this answer .

+17
source

You can count the number of properties not undefined using the abbreviation

 var length = myArr.reduce(function(len) { return len+1; }, 0); console.log(length); // 1 
+8
source

Since arrays are indexed by 0. [0...666] - 667 elements. If you really want to count the number of elements you have, an array may not be the best solution.

+5
source

You can use Object.keys () .

 Object.keys(myArr).length; 

From the documentation:

Object.keys returns an array whose elements correspond to strings for enumerable properties found directly on the object. Ordering properties is the same as setting by manually cycling through the properties of an object.

This feature is compatible with IE9 + . The documentation also contains funtion, which can be added for compatibility in all browsers:

 if (!Object.keys) Object.keys = function(o) { if (o !== Object(o)) throw new TypeError('Object.keys called on a non-object'); var k=[],p; for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p); return k; } 
+4
source

All Articles