JavaScript 如何将DOM节点列表转换为数组
NodeList对象是节点的集合,通常由诸如 Node.childNodes 和 document.querySelectorAll() 方法返回的属性返回。 虽然NodeList不是一个实际的数组,但可以使用forEach()方法对其进行迭代。 NodeList也可以通过以下方法转换为实际的数组。
方法1:使用Array.prototype.slice.call()方法
语法:
const array = Array.prototype.slice.call(nodeList); // Normal Method
const array = [].slice.call(nodeList); // Condensed Method
示例:
<body>
<p>Hello geeks 1</p>
<p>Hello geeks 2</p>
<p>Hello geeks 3</p>
<p>Hello geeks 4</p>
<script>
// This is nodeList
const nodeList = document.querySelectorAll('p');
console.log(nodeList);
// Converting using Array.prototype.slice.call
const array1 = Array.prototype.slice.call(nodeList);
console.log(array1);
</script>
</body>
输出:
方法2:使用Array.from()方法的帮助
语法:
const array = Array.from(nodeList);
示例:
<body>
<p>Hello geeks 1</p>
<p>Hello geeks 2</p>
<p>Hello geeks 3</p>
<p>Hello geeks 4</p>
<script>
// This is nodeList
const nodeList = document.querySelectorAll('p');
console.log(nodeList);
// Converting to array using Array.from() method
const array = Array.from(nodeList);
console.log(array);
</script>
</body>
输出:
方法 3:使用 ES6 扩展语法
它允许可迭代对象(如数组表达式或字符串)在期望零个或多个参数或元素的位置进行扩展。
语法:
const array = [ ...nodeList ]
示例:
<body>
<p>Hello geeks 1</p>
<p>Hello geeks 2</p>
<p>Hello geeks 3</p>
<p>Hello geeks 4</p>
<script>
// This is nodeList
const nodeList = document.querySelectorAll('p');
console.log(nodeList);
// Converting using Spread syntax
const array1 = [...nodeList];
console.log(array1);
</script>
</body>
输出:
注意: 方法2和方法3可能在旧浏览器中无法正常工作,但在所有现代浏览器中都可以正常工作。