IE从控制台调用时支持forEach(...),但在代码中调用时不支持 [英] IE supports forEach(...) when invoked fromthe console but not when called from the code

查看:1218
本文介绍了IE从控制台调用时支持forEach(...),但在代码中调用时不支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行此控制台的片段。在IE中,它按照预期产生输出。在Cr和FF中运行同样的行为来确认行为的一致性。

  [a,b]。forEach (function(element){
console.log(element);
});

但是,在运行以下脚本时,出现错误,告诉我该对象没有 forEach(...)在其上声明。这个问题发生在IE中,但不在Cr或FF中。

  var menus = document.querySelectorAll(ul.application> li>一个); 
menus.forEach(function(element){...}

变量菜单是声明的,并且选择它的元素会产生我期望的结果,即 menus [0] 存在并且是一个标记。给其他人,但它可能只是不同的演示。



我一直在祝福Cr和FF,所以我在处理IE的经验有限。我不会给你太多的智慧。



如何进一步解决问题?

解决方案基本上 document.querySelectorAll 会返回一个 nodeList 数组,像对象而不是数组。在调用数组函数之前将其转换为数组。

  var menus = document.querySelectorAll(ul.application> li> a); 
menus = [] .slice.call(menus);
menus.forEach(function(element){...});

如果您的环境支持ES6,那么您可以使用 Array.from()

  var menus = document.querySelectorAll(ul.application> li> a); 
menus = Array.from(menus);
menus.forEach(function(element){...});


I'm running this snippet the console. In IE it produces the output just as expected. Running the same in Cr and FF for reference confirms the congruence of behavior.

["a", "b"].forEach(function(element) {
  console.log(element);
});

However, when running the following script, I'm getting errors telling me that the object hasn't forEach(...) declared on it. The issue occurs in IE but not in Cr nor FF.

var menus = document.querySelectorAll("ul.application>li>a");
menus.forEach(function(element) { ... }

I've checked that the variable menus is declared and that picking it's elements produces what I would expect, i.e. menus[0] exists and is a tag. It looks a bit differently in IE compared to the others but it might be just the different rendition.

I've been blessed working with Cr and FF so my experience in dealing with IE is limited. Googling didn't give me much wisdom, neither.

How do I troubleshoot it further?

解决方案

Basically document.querySelectorAll would return a nodeList an array like object not an array. You have to convert it to an array before invoking array functions over that.

var menus = document.querySelectorAll("ul.application>li>a");
menus = [].slice.call(menus);
menus.forEach(function(element) { ... });

If your environment supports ES6 then you can use Array.from()

var menus = document.querySelectorAll("ul.application>li>a");
menus = Array.from(menus);
menus.forEach(function(element) { ... });

这篇关于IE从控制台调用时支持forEach(...),但在代码中调用时不支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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