且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 JavaScript NodeList 转换为数组的最快方法?

更新时间:2022-02-01 22:15:47

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