TL;DR The simplest reliable approach that I can think of is the following:
var count = a.filter(function() { return true; }).length;
In modern JavaScript engines, this could be shortened to:
var count = a.filter(() => true).length;
Full answer:
Checking against undefined
isn't enough because the array could actually contain undefined
values.
Reliable ways to find the number of elements are...
Use the in
operator:
var count = 0;
for (var i = 0; i < a.length; i += 1) {
if (i in a) {
count += 1;
}
}
use .forEach()
(which basically uses in
under the hood):
var a = [1, undefined, null, 7];
a[50] = undefined;
a[90] = 10;
var count = 0;
a.forEach(function () {
count += 1;
});
console.log(count); // 6
or use .filter()
with a predicate that is always true:
var a = [1, undefined, null, 7];
a[50] = undefined;
a[90] = 10;
var count = a.filter(function () { return true; }).length;
console.log(count); // 6