为什么forEach在Edge中不起作用? [英] Why is forEach not working in Edge?

查看:58
本文介绍了为什么forEach在Edge中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在Edge浏览器中不起作用.手风琴面板无法打开,出现此错误:

This code is not working in Edge browser. The accordion panel does not open and I get this error:

对象不支持属性或方法"forEach"

Object doesn't support property or method 'forEach'

const accordionBtn = document.querySelectorAll('.btn-accordion');

accordionBtn.forEach(item => item.addEventListener('click', e => {
    e.preventDefault();

    const currItem = e.currentTarget;

    currItem.classList.toggle("open");
}))

推荐答案

请注意,这应该在Edge 16+和其他浏览器的最新版本中均有效

Note this should work in Edge 16+ and across the latest versions of other browsers according to MDN. I manually tested Edge 17 and verified it works there.

问题源于所有浏览器中 querySelectorAll 返回 NodeList 而不是 Array 的事实.虽然 Array 支持 forEach 已有一段时间,但直到最近,API才被添加到 NodeList .

The issue stems from the fact that querySelectorAll returns a NodeList instead of an Array in all browsers. While Array has supported forEach for some time, only more recently has the API been added to NodeList.

如果您想使用它并需要支持较旧的浏览器版本,则可以通过复制 Array 本身的实现(在IE9 +中有效)来创建简单的polyfill:

If you want to use this and need to support older browser versions, you can create a trivial polyfill by copying the implementation from Array itself (works in IE9+):

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

过滤器地图如何?

还值得注意的是, filter map 等许多其他有用的API仍然不存在于 NodeList 中.浏览器.因此,如果您想获得完整的体验,最好的选择是将项目复制到 real Array .

What about filter and map?

Also worth noting is that a number of other helpful APIs like filter and map still do not exist on NodeList in any browser. Therefore if you want the full experience, your best bet is to copy the items into a real Array.

在大多数现代浏览器中,都可以使用 Array.from(nodelist) 或通过

In most modern browsers this can be done using Array.from(nodelist) or via the spread syntax [...nodelist]. However, if you need to support IE you can use slice (among other creative techniques) to get the job done:

var arr = Array.prototype.slice.call(nodelist);

这篇关于为什么forEach在Edge中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆