有更有效的方法来转换一个HTMLCollection到数组,而不是通过迭代的内容说集合和手动推每个项目到数组?
当前回答
这适用于所有浏览器,包括早期的IE版本。
var arr = [];
[].push.apply(arr, htmlCollection);
由于jsperf目前仍处于关闭状态,下面是一个比较不同方法性能的jsfiddle。https://jsfiddle.net/qw9qf48j/
其他回答
这是我个人的解决方案,基于这里的信息(这篇文章):
var Divs = new Array();
var Elemns = document.getElementsByClassName("divisao");
try {
Divs = Elemns.prototype.slice.call(Elemns);
} catch(e) {
Divs = $A(Elemns);
}
Gareth Davis在他的帖子中描述了$A:
function $A(iterable) {
if (!iterable) return [];
if ('toArray' in Object(iterable)) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
如果浏览器支持最好的方式,否则将使用跨浏览器。
对于跨浏览器的实现,我建议你看看prototype.js $ a函数
从1.6.1复制:
function $A(iterable) {
if (!iterable) return [];
if ('toArray' in Object(iterable)) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
它没有使用Array.prototype.slice,可能是因为它不是在每个浏览器上都可用。我担心性能是相当糟糕的,因为有一个回落是一个javascript循环迭代。
这适用于所有浏览器,包括早期的IE版本。
var arr = [];
[].push.apply(arr, htmlCollection);
由于jsperf目前仍处于关闭状态,下面是一个比较不同方法性能的jsfiddle。https://jsfiddle.net/qw9qf48j/
I suppose that calling Array.prototype functions on instances of HTMLCollection is a much better option than converting collections to arrays (e.g.,[...collection] or Array.from(collection)), because in the latter case a collection is unnecessarily implicitly iterated and a new array object is created, and this eats up additional resources. Array.prototype iterating functions can be safely called upon objects with consecutive numeric keys starting from [0] and a length property with a valid number value of such keys' quantity (including, e.g., instances of HTMLCollection and FileList), so it's a reliable way. Also, if there is a frequent need in such operations, an empty array [] can be used for quick access to Array.prototype functions; or a shortcut for Array.prototype can be created instead. A runnable example:
原型机; 收集=文件。getElementById(ol).子女: 警报(的减少。呼叫(收集,(acc,发短信),i => 回回acc += 1) 的,”); < ol id =“ol”> < li > foo < / li > < li > < / li >酒吧 < li >蝙蝠< / li > < li >巴兹< / li > < / ol >
我看到了一个更简洁的获取Array的方法。原型方法一般来说也很有效。将HTMLCollection对象转换为Array对象的演示如下:
[].slice.call( yourHTMLCollectionObject );
而且,正如评论中提到的,对于老式浏览器,比如IE7和更早的版本,你只需要使用兼容性函数就可以了,比如:
function toArray(x) {
for(var i = 0, a = []; i < x.length; i++)
a.push(x[i]);
return a
}
我知道这是一个老问题,但我觉得公认的答案有点不完整;所以我想先把这个扔出去。