我试图在HTMLCollectionOf中设置所有元素的获取id。我写了下面的代码:

var list = document.getElementsByClassName("events");
console.log(list[0].id);
for (key in list) {
    console.log(key.id);
}

但我在控制台得到以下输出:

event1
undefined

这和我预料的不一样为什么第二个控制台输出是未定义的,而第一个控制台输出是event1?


当前回答

如果你使用ES的旧版本(例如ES5),你可以使用as any:

for (let element of elementsToIterate as any) {
      console.log(element);
}

其他回答

我经常用的简单方法

let list = document.getElementsByClassName("events");
let listArr = Array.from(list)

在此之后,您可以在选择上运行任何所需的Array方法

listArr.map(item => console.log(item.id))
listArr.forEach(item => console.log(item.id))
listArr.reverse()

在边缘

if(!NodeList.prototype.forEach) {
  NodeList.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}

你想把它改成

var list= document.getElementsByClassName("events");
console.log(list[0].id); //first console output
for (key in list){
    console.log(list[key].id); //second console output
}

Array.from的替代方法是使用Array.prototype.forEach.call

forEach: Array.prototype.forEach。call(htmlCollection, i => {console.log(i)});

地图:Array.prototype.map。call(htmlCollection, i => {console.log(i)});

你不能在nodelist或HTMLCollections上使用for/in。但是,您可以使用一些数组。原型方法,只要你.call()他们,并传递在NodeList或HTMLCollection像这样。

因此,可以考虑以下代码作为jfriend00 for循环的替代:

var list= document.getElementsByClassName("events");
[].forEach.call(list, function(el) {
    console.log(el.id);
});

MDN上有一篇很好的文章介绍了这种技术。注意他们关于浏览器兼容性的警告:

[…传递一个宿主对象(像一个NodeList)作为 对于本地方法(如forEach),这并不保证能工作 所有的浏览器和已知的失败在一些。

因此,虽然这种方法很方便,但for循环可能是最兼容浏览器的解决方案。

更新(2014年8月30日):最终你将能够使用ES6 /of!

var list = document.getElementsByClassName("events");
for (const el of list)
  console.log(el.id);

最近版本的Chrome和Firefox已经支持它了。