Lately, we've been heavily using javascript arrays and hashes and trying to find a universal way to count the items in both without needing to differentiate between the two. The .length method has proved to be unreliable as it only returns the value of the highest index in an array. The code snippet below attempts to solve this issue, but runs into problems with hashes returning inaccurate length values. We initially switched to Object.keys().length, but faced compatibility issues with older browsers like IE8.
We're stuck on such a simple problem and need some guidance. Help me, Obi Wan Kenobi. You're my only hope!
function isNullOrUndefined(aObject) {
"use strict";
return (typeof aObject === 'undefined' || aObject === null);
}
function count(aList) {
"use strict";
var lKey = null,
lResult = 0;
if (!isNullOrUndefined(aList)) {
if (aList.constructor == Array) {
lResult = aList.length;
} else if (!isNullOrUndefined(Object.keys)) {
lResult = Object.keys(aList).length;
} else {
for (lKey in aList) {
if (aList.hasOwnProperty(lKey)) {
lResult++;
}
}
}
}
return lResult;
}