javascript中类似数组的对象 [英] Array-like object in javascript
问题描述
查看Closure库中的dom.js源代码,我发现了这个(在 goog.dom.getElementsByTagNameAndClass _
中):
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?
推荐答案
代码的作者使用空的JavaScript对象作为对象数组的基础,即可以通过索引访问的数组有一个长度属性。
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.
我可以想到两个原因:
- 内存使用 - 如果数组由分配n个元素的实现支持,当它达到它的限制时,它会增加一些因素来增加它的容量,因此浪费
capacity - length
of memory - cpu time - 实现者选择插入速度超过随机访问速度 - 此方法的返回更有可能比随机访问顺序迭代,并在插入时调整数组大小导致具有cpu惩罚的allocate-copy-deallocation
- 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
我打赌在其他JavaSc中会找到类似的代码ript库,它是基准测试的结果,并且可以在不同的浏览器中找到最适合的解决方案。
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.
在Justin发表评论之后编辑
进一步谷歌搜索后,似乎类似数组的对象在JavaScript开发人员中很常见:checkout JavaScript:David Flanagan的权威指南,它有一个整体关于类数组对象的子章节。另外这些 < a href =http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript =nofollow noreferrer>伙计们提及它们。
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.
所以第三个选项可能是关键:符合JavaScript API的规范。
So a third option could be the key: compliance with norms of JavaScript API's.
这篇关于javascript中类似数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!