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:
- memory use - if array is backed by implementation that allocates n elements, when it reaches it's limits it grows by some factor to increase it's capacity, and thusly wastes
capacity - length
of memory
- cpu time - implementor choose insertion speed over random access speed -- a return from this method is more likely to be iterated over sequentially than random accessed, and resizing the array in insertion causes allocation-copy-deallocation which has a cpu penalty
I'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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…