将 HTMLCollection 转换为数组的最有效方法 [英] Most efficient way to convert an HTMLCollection to an Array
问题描述
除了遍历所述集合的内容并手动将每个项目推送到数组之外,是否有更有效的方法将 HTMLCollection 转换为数组?
Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?
推荐答案
var arr = Array.prototype.slice.call( htmlCollection )
使用本机"代码也有同样的效果.
will have the same effect using "native" code.
编辑
由于这得到了很多观点,请注意(根据@oriol 的评论)以下更简洁的表达有效等效:
Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is effectively equivalent:
var arr = [].slice.call(htmlCollection);
但是请注意@JussiR 的评论,与详细"形式不同,它确实在此过程中创建了一个空的、未使用的且实际上无法使用的数组实例.编译器对此的处理超出了程序员的能力范围.
But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.
编辑
自 ECMAScript 2015 (ES 6) 起,还有 Array.from:
Since ECMAScript 2015 (ES 6) there is also Array.from:
var arr = Array.from(htmlCollection);
编辑
ECMAScript 2015 还提供了传播运算符,它在功能上等同于 Array.from
(尽管请注意 Array.from
支持映射函数作为第二个参数).
ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from
(although note that Array.from
supports a mapping function as the second argument).
var arr = [...htmlCollection];
我已经确认上述两项都适用于 NodeList
.
I've confirmed that both of the above work on NodeList
.
上述方法的性能比较:http://jsben.ch/h2IFA
这篇关于将 HTMLCollection 转换为数组的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!