可以使用Array.prototype.slice.call()方法将HTMLCollection/NodeList/伪数组转换成数组,示例如下:,,“javascript,var htmlCollection = document.getElementsByTagName('div');,var nodeList = document.querySelectorAll('div');,var pseudoArray = {0: 'a', 1: 'b', 2: 'c', length: 3};,,var arrayFromHtmlCollection = Array.prototype.slice.call(htmlCollection);,var arrayFromNodeList = Array.prototype.slice.call(nodeList);,var arrayFromPseudoArray = Array.prototype.slice.call(pseudoArray);,“
将HTMLCollection/NodeList/伪数组转换成数组的实现方法JavaScript
在JavaScript中,我们经常会遇到HTMLCollection和NodeList这样的对象,它们类似于数组,但并不具备所有数组的方法,为了更方便地操作这些对象,我们可以将它们转换为真正的数组,以下是几种常见的转换方法:
使用Array.prototype.slice.call()
let nodeList = document.querySelectorAll('div'); // 假设获取到的是一组div元素
let array = Array.prototype.slice.call(nodeList); 使用Array.from()
let nodeList = document.querySelectorAll('div'); // 假设获取到的是一组div元素
let array = Array.from(nodeList); 使用扩展运算符(Spread Operator)
let nodeList = document.querySelectorAll('div'); // 假设获取到的是一组div元素
let array = [...nodeList]; 使用for循环遍历
let nodeList = document.querySelectorAll('div'); // 假设获取到的是一组div元素
let array = [];
for (let i = 0; i < nodeList.length; i++) {
array.push(nodeList[i]);
} 单元表格比较各种方法的性能
Array.prototype.slice.call()Array.from()扩展运算符for循环遍历相关问题与解答栏目
问题1: 如何判断一个变量是否为数组?
答案: 可以使用Array.isArray()方法来判断一个变量是否为数组。
let arr = [1, 2, 3]; console.log(Array.isArray(arr)); // 输出 true
问题2: 如何判断一个变量是否为HTMLCollection或NodeList?
答案: HTMLCollection和NodeList都是类数组对象,但它们没有标准的instanceof检测方式,一种常用的方法是检查对象是否有特定的属性或方法,如length属性和item方法。
function isNodeListOrHTMLCollection(obj) {
return obj instanceof NodeList || obj instanceof HTMLCollection;
} 本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/40517.html