使用 for-of 循​​环迭代 HTMLCollection 对象

Iterating an HTMLCollection object using for-of loop

我正在使用 babel-polyfill and I'm trying to iterate an HTMLCollection 使用 for-of 循​​环的对象:

const elements = document.getElementsByClassName('some-class')
for (const element of elements) {
  console.log(element)
}

它不起作用。我遇到错误 elements[Symbol.iterator] is not a function。如何让它正常工作?

来自 "Iterable DOM collections" on the core-js GitHub page:

Some DOM collections should have iterable interface or should be inherited from Array. That mean they should have keys, values, entries and @@iterator methods for iteration. So add them. Module web.dom.iterable:

{
  NodeList,
  DOMTokenList,
  MediaList,
  StyleSheetList,
  CSSRuleList
}
  #values()     -> iterator
  #keys()       -> iterator
  #entries()    -> iterator
  #@@iterator() -> iterator (values)

如您所见,该列表不包括 HTMLCollection。为了能够使用 HTMLCollection 的 for-of 循​​环,您必须手动将 Array.prototype.values 分配给 HTMLCollection.prototype[Symbol.iterator]。看这个例子:

HTMLCollection.prototype[Symbol.iterator] = Array.prototype.values

for (const element of document.getElementsByTagName('a')) {
  console.log(element.href)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.min.js"></script>
<a href="//www.google.com">Google</a>
<a href="//www.github.com">GitHub</a>

或者,您可以只使用 document.querySelectorAll(),这是一个 returns 一个 NodeList 对象。