2016-09-29 198 views
2

我使用babel-polyfill,我尝试使用换的循环迭代的HTMLCollection对象的HTMLCollection对象:迭代使用-的循环

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

它不工作。我收到错误elements[Symbol.iterator] is not a function。如何使其正确工作?

+0

解释一些你误解的东西:core-js是babel-polyfill的一部分,所以将它包含两次没有意义。如果在控制台中键入“Symbol.iterator”,它只意味着此符号存在;它并不一定意味着'elements'具有'Symbol.iterator'属性。 for-of循环不会将任何对象视为数组,它只是调用对象的“@@ iterator”方法。 –

+0

另外,如果您不知道什么是HTMLCollection对象:它是由'document.getElementsByClassName()'返回的对象。 –

+0

@Gothdo,为了澄清,我从未包含core-js和babel-polyfill:我刚刚尝试在不同时间导入它们以查看其中一个或另一个是否有效。尽管如此,谢谢你的澄清。 – thesublimeobject

回答

3

"Iterable DOM collections" on the core-js GitHub page

一些DOM集合应该有iterable interface还是应该 inherited from Array。这意味着 他们应该有keysvalues,entries@@iterator方法 迭代。所以添加它们。模块 web.dom.iterable

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

正如你可以看到,该名单不包括HTMLCollection。为了能够使用HTMLCollection的for-for循环,您必须手动将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(),其中回报NodeList对象。

+0

@ zer00ne添加到答复。 –

+0

@Gothdo这是一个非常有用的答案。非常感谢你。我误解了可迭代规范,现在明白我为什么会遇到这个问题。 – thesublimeobject