JavaScript 将NodeList转换为数组的最快方法
NodeList 是类似数组的节点集合。它基本上是DOM元素的集合。为了使用NodeList,我们可以将其转换为普通的JavaScript数组,以便使用数组的特性和灵活性。NodeList是宿主对象,不受适用于原生JavaScript对象的常规规则的限制。
方法: 有很多方法可以将NodeList转换为JavaScript数组,但其中最快的方法是ES6中的一个新方法。在ES6中,我们现在可以使用 Array.from() 方法简单地从NodeList中创建一个数组。该方法用于从类似数组或可迭代对象创建浅复制的新数组实例。我们要转换的NodeList在这种情况下是类似数组的对象。
语法:
let my_arr = Array.from( given_nodelist )
示例: 此示例展示了上述解释的方法的使用。
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<div class="content primary">
<p>
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and
placement guides.
</p>
</div>
<div class="content secondary">
<p>This example demonstrates the fastest
way to convert from a NodeList to an array.
</p>
</div>
<script>
// This will act select all div DOM
elements in the page
let nodelist =
document.querySelectorAll('div');
// This will convert the DOM NodeList
// to a JavaScript Array Object
let my_arr = Array.from(nodelist);
// Display the array in the console
console.log(my_arr);
// Display all the values of the
// array in the console
for (let val of my_arr) {
console.log(val);
}
</script>
</body>
输出: