Cette page a été traduite à partir de l'anglais par la communauté.Vous pouvez contribuer en rejoignant la communauté francophone sur MDN Web Docs.
SyntaxError: a declaration in the head of a for-of loop can't have an initializer
Message
SyntaxError: for-of loop head declarations cannot have an initializer (Edge)SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)SyntaxError: for-of loop variable declaration may not have an initializer. (Chrome)
Dans cet article
Type d'erreur
SyntaxErrorQuel est le problème ?
L'en-tête d'une bouclefor...of contient une expression d'initialisation, c'est-à-dire qu'une variable est déclarée et qu'on lui affecte une valeur. Ceci n'est pas autorisé pour les bouclesfor-of. En revanche, les bouclesfor permettent d'avoir un initialisateur.
Exemples
>Bouclesfor-of invalides
js
let iterable = [10, 20, 30];for (let value = 50 of iterable) { console.log(value);}// SyntaxError: a declaration in the head of a for-of loop can't// have an initializerBouclesfor-of valides
Il faut retirer l'initialisateur de l'en-tête de la boucle pour ne plus avoir l'erreur. Si cette valeur devait servir d'incrément, on peut ajouter l'addition dans le corps de la boucle.
js
let iterable = [10, 20, 30];for (let value of iterable) { value += 50; console.log(value);}// 60// 70// 80Voir aussi
for...offor...ininterdit également d'utiliser un initialisateur en mode strict (SyntaxError: for-in loop head declarations may not have initializers)forpermet de définir un initialisateur lors de l'itération