在getElementsByClassName的数组上使用forEach会导致"TypeError:undefined不是函数"

Jer*_*Jer 90 javascript foreach

我的JSFiddle中,我只是试图遍历一个元素数组.正如日志语句所证明的那样,该数组是非空的.然而这个电话给forEach了我(不是那么有帮助)"Uncaught TypeError:undefinedis not a function"错误.

我必须做一些愚蠢的事; 我究竟做错了什么?

我的代码:

var arr = document.getElementsByClassName('myClass');
console.log(arr);
console.log(arr[0]);
arr.forEach(function(v, i, a) {
  console.log(v);
});
Run Code Online (Sandbox Code Playgroud)
.myClass {
  background-color: #FF0000;
}
Run Code Online (Sandbox Code Playgroud)
<div class="myClass">Hello</div>
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 161

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

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

[].forEach.call(document.getElementsByClassName('myClass'), function(v,i,a) {
Run Code Online (Sandbox Code Playgroud)

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

Array.from(document.getElementsByClassName('myClass')).forEach(v=>{
Run Code Online (Sandbox Code Playgroud)

或者将类数组的对象传播到数组中:

[...document.getElementsByClassName('myClass'))].forEach(v=>{
Run Code Online (Sandbox Code Playgroud)

  • @Jer`参数`是一个.jQuery对象是另一个.你可以自己做一个:`var a = {"0":"str1","1":"str2",长度:2}` (2认同)
  • @Jer:如果您打算因任何原因打破循环,那么作为旁注:"Array.prototype.forEach"将不允许您这样做.如果您有此要求,请稍后使用标准`for`循环,或者如果您想使用数组对象,请使用`Array.prototype.every`或`Array.prototype.some`(请注意,IE8中不支持每个/某些)减) (2认同)

小智 11

试试这个它应该工作:

<html>
  <head>
    <style type="text/css">
    </style>
  </head>
  <body>
   <div class="myClass">Hello</div>
   <div class="myClass">Hello</div>

<script type="text/javascript">
    var arr = document.getElementsByClassName('myClass');
    console.log(arr);
    console.log(arr[0]);
    arr = [].slice.call(arr); //I have converted the HTML Collection an array
    arr.forEach(function(v,i,a) {
        console.log(v);
    });
</script>


<style type="text/css">
    .myClass {
    background-color: #FF0000;
}
</style>

  </body>
</html>
Run Code Online (Sandbox Code Playgroud)