blog
blog copied to clipboard
IE10以下报错:SCRIPT438: 对象不支持“forEach”属性或方法
描述
IE10以下报错:SCRIPT438: 对象不支持“forEach”属性或方法
运行环境
浏览器类型和版本:IE IE10以下
操作系统:windows
操作步骤
//获取dom元素 const list = document.querySelectorAll('.level-li'); //循环 list.forEach((li, liIndex) => { .... })
现象描述及期望行为
正确的循环list
当前的状况
IE下报错
SCRIPT438: 对象不支持“forEach”属性或方法
相关代码
运行结果
解决方案
document.querySelectorAll()返回的不是一个数组,而是一个NodeList; 而NodeList再IE10以下并没有forEach方法,需要Polyfill,方案如下:
if (window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = function (callback, thisArg) { thisArg = thisArg || window; for (var i = 0; i或者:
if (window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; }参照:
https://developer.mozilla.org/zh-CN/docs/Web/API/NodeList/forEach