2016-09-29 201 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