更新时间:2022-02-01 22:15:47
所以你可以简单地做:
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
Map
和 Set
等对象)HTMLCollection
returned by e.g. document.getElementsByTagName
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);