Looking through the dom.js source from the Closure library I found this (in goog.dom.getElementsByTagNameAndClass_
):
if (opt_class) {
var arrayLike = {};
var len = 0;
for (var i = 0, el; el = els[i]; i++) {
var className = el.className;
// Check if className has a split function since SVG className does not.
if (typeof className.split == 'function' &&
goog.array.contains(className.split(' '), opt_class)) {
arrayLike[len++] = el;
}
}
arrayLike.length = len;
return arrayLike;
}
What would be the benefit of doing this over a regular array?
The author of the code used empty JavaScript object as a basis of a array like object, i.e. the one that can be accessed by index and has a length property.
There could be two reasons that I could think of:
capacity - length
of memoryI'm betting that similar code would be found in other JavaScript libraries, and that it's result of benchmarking and finding the best to fit solution across different browsers.
edited after comment by Justin
Upon further googling it appears that array-like objects are common among JavaScript developers: checkout JavaScript: the definitive guide by David Flanagan, it has a whole sub-chapter on Array-like objects. Also these guys mention them.
No mention of why should one prefer array-like vs array object. This could be a good SO question.
So a third option could be the key: compliance with norms of JavaScript API's.