SyntaxError: a declaration in the head of a for-of loop can't have an initializer

Наши волонтёры ещё не перевели данную статью на Русский. Присоединяйтесь к нам и помогите сделать эту работу!
Вы можете также прочитать эту статью на English (US).

Message

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)

Error type

SyntaxError

What went wrong?

The head of a for...of loop contains an initializer expression. That is, a variable is declared and assigned a value |for (var i = 0 of iterable)|. This is not allowed in for-of loops. You might want a for loop that does allow an initializer.

Examples

Invalid for-of loop

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 initializer

Valid for-of loop

You need to remove the initializer (value = 50) in the head of the for-of loop. Maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example.

let iterable = [10, 20, 30];

for (let value of iterable) {
  value += 50;
  console.log(value);
}
// 60
// 70
// 80

See also

Метки документа и участники

Метки: 
 Внесли вклад в эту страницу: fscholz
 Обновлялась последний раз: fscholz,