将 JavaScript NodeList 转换为数组的最快方法? [英] Fastest way to convert JavaScript NodeList to Array?

查看:67
本文介绍了将 JavaScript NodeList 转换为数组的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前在这里回答的问题说这是最快的方法:

Previously answered questions here said that this was the fastest way:

//nl is a NodeList
var arr = Array.prototype.slice.call(nl);

在我的浏览器上进行基准测试时,我发现它比这个慢 3 倍多:

In benchmarking on my browser I have found that it is more than 3 times slower than this:

var arr = [];
for(var i = 0, n; n = nl[i]; ++i) arr.push(n);

它们都产生相同的输出,但我发现很难相信我的第二个版本是最快的方式,尤其是因为人们在这里另有说法.

They both produce the same output, but I find it hard to believe that my second version is the fastest possible way, especially since people have said otherwise here.

这是我的浏览器 (Chromium 6) 的怪癖吗?或者有没有更快的方法?

Is this a quirk in my browser (Chromium 6)? Or is there a faster way?

对于任何关心的人,我确定了以下内容(这似乎是我测试过的每个浏览器中最快的):

For anyone who cares, I settled on the following (which seems to be the fastest in every browser that I tested):

//nl is a NodeList
var l = []; // Will hold the array of Node's
for(var i = 0, ll = nl.length; i != ll; l.push(nl[i++]));

我找到了一种更快的方法

I found an even faster way

// nl is the nodelist
var arr = [];
for(var i = nl.length; i--; arr.unshift(nl[i]));

推荐答案

2021 更新:nodeList.forEach() 现在是标准的 并且在所有当前浏览器中都受支持(周围95% 在桌面和移动设备上).

所以你可以简单地做:

2021 update: nodeList.forEach() is now standard and supported in all current browsers (around 95% on both dekstop & mobile).

So you can simply do:

document.querySelectorAll('img').forEach(highlight);


其他情况

如果您出于某种原因想要将其转换为数组,而不仅仅是对其进行迭代 - 这是一个完全相关的用例 - 您可以使用 [...destructuring]Array.from 自 ES6

If you for some reason want to convert it to an array, not just iterate over it - which is a completely relevant use-case - you can use [...destructuring] or Array.from since ES6

let array1 = [...mySetOfElements];
// or
let array2 = Array.from(mySetOfElements);

这也适用于非 NodeLists 的其他类似数组的结构

This also works for other array-like structures that aren't NodeLists

  • HTMLCollection 由例如返回document.getElementsByTagName
  • 具有长度属性和索引元素的对象
  • 可迭代对象(MapSet 等对象)
  • HTMLCollection returned by e.g. document.getElementsByTagName
  • objects with a length property and indexed elements
  • iterable objects (objects such as Map and Set)

过时的 2010 年答案

第二个在某些浏览器中往往更快,但重点是您必须使用它,因为第一个不是跨浏览器.尽管时代在变

The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'

@kangax(IE 9 预览)

Array.prototype.slice 现在可以转换某些主机对象(例如 NodeList 的)到数组 - 大多数现代浏览器已经能够做到好一阵子了.

Array.prototype.slice can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.

示例:

Array.prototype.slice.call(document.childNodes);

这篇关于将 JavaScript NodeList 转换为数组的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆