You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:01:06