有更有效的方法来转换一个HTMLCollection到数组,而不是通过迭代的内容说集合和手动推每个项目到数组?


当前回答

这是我个人的解决方案,基于这里的信息(这篇文章):

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;
}

如果浏览器支持最好的方式,否则将使用跨浏览器。

其他回答

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 >

这适用于所有浏览器,包括早期的IE版本。

var arr = [];
[].push.apply(arr, htmlCollection);

由于jsperf目前仍处于关闭状态,下面是一个比较不同方法性能的jsfiddle。https://jsfiddle.net/qw9qf48j/

为了高效地将类数组转换为数组,我们可以使用jQuery makeArray:

makeArray:将一个类似数组的对象转换为一个真正的JavaScript数组。

用法:

var domArray = jQuery.makeArray(htmlCollection);

额外的一点:

如果你不想保持对数组对象的引用(大多数情况下HTMLCollections是动态变化的,所以最好将它们复制到另一个数组中,这个例子密切关注性能:

var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length
var resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.

for (var i = 0 ; i < domDataLength ; i++) {
    resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.
}

什么是类数组?

HTMLCollection是一个“类数组”对象,类数组对象类似于array的对象,但缺少很多函数定义:

类数组对象看起来像数组。它们有不同的编号 元素和length属性。但相似之处仅此而已。 类数组对象不具有Array的任何函数,而for-in 循环甚至不起作用!

有时候,即使你以正确的方式写了代码,但它仍然不能正常工作。

var allbuttons = document.getElementsByTagName("button");
console.log(allbuttons);

var copyAllButtons = [];
for (let i = 0; i < allbuttons.length; i++) {
  copyAllButtons.push(allbuttons[i]);
}
console.log(copyAllButtons);

你得到一个空数组。 喜欢,这

HTMLCollection []
[]

Console_javascript

为了解决这个问题,你必须在html文件的body标签后添加javascript文件的链接。

<script src="./script.js"></script>

如下图所示, html_file

最终输出

HTMLCollection(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b, b: button#b]
(6) [button.btn.btn-dark.click-me, button.btn.btn-dark.reset, button#b, button#b, button#b, button#b]

对于跨浏览器的实现,我建议你看看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循环迭代。