在来自 getElementsByClassName 的数组上使用 forEach 会导致“TypeError: undefined is not a function" [英] Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function”

查看:18
本文介绍了在来自 getElementsByClassName 的数组上使用 forEach 会导致“TypeError: undefined is not a function"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 JSFiddle 中,我只是尝试遍历元素数组.正如日志语句所证明的那样,该数组是非空的.然而对 forEach 的调用给了我(不是很有帮助)Uncaught TypeError: undefined is not a function"错误.

In my JSFiddle, I’m simply trying to iterate over an array of elements. The array is non-empty, as the log statements prove. Yet the call to forEach gives me the (not so helpful) "Uncaught TypeError: undefined is not a function" error.

我一定是在做蠢事;我做错了什么?

I must be doing something stupid; what am I doing wrong?

我的代码:

var arr = document.getElementsByClassName('myClass');
console.log(arr);
console.log(arr[0]);
arr.forEach(function(v, i, a) {
  console.log(v);
});

.myClass {
  background-color: #FF0000;
}

<div class="myClass">Hello</div>

推荐答案

那是因为 document.getElementsByClassName 返回一个 HTMLCollection,不是数组.

That's because document.getElementsByClassName returns a HTMLCollection, not an array.

幸运的是,它是一个 "类似数组的" object(这解释了为什么将它记录为一个对象,以及为什么您可以使用标准的 for 循环进行迭代),因此您可以这样做:

Fortunately it's an "array-like" object (which explains why it's logged as if it was an object and why you can iterate with a standard for loop), so you can do this :

[].forEach.call(document.getElementsByClassName('myClass'), function(v,i,a) {

使用 ES6(在现代浏览器或 Babel 上),您还可以使用 Array.from 从类数组对象构建数组:

With ES6 (on modern browsers or with Babel), you may also use Array.from which builds arrays from array-like objects:

Array.from(document.getElementsByClassName('myClass')).forEach(v=>{

或将类数组对象展开成数组:

or spread the array-like object into an array:

[...document.getElementsByClassName('myClass'))].forEach(v=>{

这篇关于在来自 getElementsByClassName 的数组上使用 forEach 会导致“TypeError: undefined is not a function"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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