问题
I am building an Array with
const myCanvas = documen.getElementsByTagName('canvas')
that it's actually working. It returns me something like this:
images: [
0: canvas,
1: canvas,
2: canvas
]
This is for a Typescript project, I want to iterate this Array and transform each image in order to log it.
Like this:
for (const image of myCanvas) {
console.log(canvas.toDataURL());
}
(I am not using foreach because it doesn't works with HTMLCollectionOf type)
I need to iterate the HTMLCollection that getElementsByTagName is returning me. The output is Type 'HTMLCollectionOf' must have a 'Symbol.iterator' method that returns an iterator
回答1:
It may be worth checking your TypeScript / definitions version, because I get no errors. I believe the errors relate to some older browsers actually not supporting iteration of the HTML collection, so you could use a traditional for loop.
Both examples shown below:
const myCanvas: HTMLCollectionOf<HTMLCanvasElement> = document.getElementsByTagName('canvas');
for (const image of myCanvas) {
console.log(image.toDataURL());
}
for (let i = 0; i < myCanvas.length; i++) {
console.log(myCanvas[i].toDataURL());
}
回答2:
In order to iterate that way you need to set compilerOptions
like this:
"compilerOptions": {
// ...
"target": "ES6",
"lib": [
"DOM",
"DOM.Iterable",
"ES6"
]
// ...
}
来源:https://stackoverflow.com/questions/57621104/type-htmlcollectionofhtmlcanvaselement-must-have-a-symbol-iterator-met