解决NodeList类型(类数组对象)在低版本浏览器中不支持forEach -- 工作笔记

mac2024-05-27  49

var nodes = document.querySelectorAll(className);

这里a得到的是一个NodeList类型的一个实例; NodeList是一个类数组对象:与数组一样具有length与index属性,但本质是Object; 是下面这种形式

NodeList { 0: [object HTMLDivElement], 1: [object HTMLDivElement], .... }

该实例对象在低版本浏览器不支持forEach方法,会报错 类似下面这样的错误。

TypeError: nodes.forEach is not a function. (In 'nodes.forEach', 'nodes.forEach' is undefined)

解决方式

原本代码 const nodes = document.querySelectorAll(className); nodes.forEach((el, idx) => { //Todo }) //改法一 Array.prototype.forEach.call(nodes,(el, idx) => { //ToDo }) //改法二(推荐) Array.from(nodes).forEach((el, idx) => { //Todo })

本质都是让其能够使用真正的数组的forEach方法。

最新回复(0)