在 JavaScript 中,将 NodeList 转换为数组的最佳方法是什么? [英] In JavaScript, what is the best way to convert a NodeList to an array?
本文介绍了在 JavaScript 中,将 NodeList 转换为数组的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
DOM 方法 document.querySelectorAll()
(以及其他一些方法)返回一个 NodeList
.
The DOM method document.querySelectorAll()
(and a few others) return a NodeList
.
对列表进行操作,例如使用forEach()
,必须先将NodeList
转换为Array
.
To operate on the list, e.g. using forEach()
, the NodeList
must first be converted to an Array
.
将 NodeList
转换为 Array
的最佳方法是什么?
What's the best way to convert the NodeList
to an Array
?
推荐答案
使用 ES6,您可以简单地做到:
With ES6 you can simply do:
const spanList = [...document.querySelectorAll("span")];
这篇关于在 JavaScript 中,将 NodeList 转换为数组的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文