为何forEach在Safari9等应有支持的旧浏览器中无法运行?
问题原因及解决方案
你的代码报错是因为**querySelectorAll返回的是NodeList对象**,而你提到的这些旧浏览器(Safari 9、Chrome 49、部分旧Firefox版本)并不支持NodeList原生的forEach方法——你在CanIUse上查到的forEach支持是针对数组的,而非NodeList的。
解决方法
方法1:将NodeList转为数组后使用forEach
可以用Array.prototype.slice.call把NodeList转为数组(Safari 9不支持Array.from,这个方法兼容性更好):
const features_blocks = document.querySelectorAll('#feature-blocks .block'); const featuresArray = Array.prototype.slice.call(features_blocks); featuresArray.forEach(f => { // 你的逻辑 });
方法2:直接调用数组的forEach方法处理NodeList
无需转数组,直接借助Array.prototype.forEach来遍历NodeList:
const features_blocks = document.querySelectorAll('#feature-blocks .block'); Array.prototype.forEach.call(features_blocks, f => { // 你的逻辑 });
方法3:使用普通for循环兜底
如果不想依赖原型方法,直接用传统for循环最兼容:
const features_blocks = document.querySelectorAll('#feature-blocks .block'); for (let i = 0; i < features_blocks.length; i++) { const f = features_blocks[i]; // 你的逻辑 }
补充说明
NodeList.prototype.forEach是后续才加入浏览器标准的:Chrome从51版本开始支持,Firefox从50版本开始,Safari则要到10版本才支持——这就是旧版本浏览器报错的核心原因,而CanIUse的默认查询结果没区分开数组和NodeList的forEach支持范围。
内容的提问来源于stack exchange,提问作者Andrew Newby
相关产品推荐
相关产品推荐

