I tried this way, but it returns me the wrong count:
myArr = [];
myArr[666] = 'hello there';
console.log(myArr.length); // returns me 667
It should be 1. How can I have the good count in the fastest way?
It should be 1.
No, it should be 667, because that's how length
is defined for standard arrays in JavaScript, which aren't really arrays at all. Arrays in JavaScript are inherently sparse, meaning they can have holes in them (indexes where no value of any kind is stored).
How can I have the good count in the fastest way?
The only way is by looping. For instance:
var count = 0;
myArr.forEach(function() {
++count;
});
console.log(count);
...or via reduce
as in maček's answer. forEach
, reduce
, and other such only visit entries that actually exist, so they skip the holes in sparse arrays.
I should mention that since IE8 still (sigh) has a fair bit of market share, you need to shim forEach
and reduce
and such on it if you want to use them. (Which is easy.)
To do this without any shimming, and only count actual index properties (not other kinds of properties), then loosely:
var count = 0, name;
for (name in myArr) {
if (myArr.hasOwnProperty(name) && /^[0-9]+$/.test(name)) {
++count;
}
}
That uses a slightly loose definition of what an index property name is; if you want a robust one, see the "Use for-in correctly" part of this answer.
You can count the number of non-undefined properties using a reduce
var length = myArr.reduce(function(len) { return len+1; }, 0);
console.log(length); // 1
Because arrays are indexed by 0. [0...666]
is 667 items. If you actually want a count of how many items you have, an array might not be the best solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With