语法错误:for-of 循环头部的声明不能有初始值设定项

for...of 循环的头部包含初始化表达式(例如 for (const i = 0 of iterable))时,会发生 JavaScript 异常 "for-of 循环头部的声明不能有初始值设定项"。这在 for-of 循环中是不允许的。

¥The JavaScript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a for...of loop contains an initializer expression such as for (const i = 0 of iterable). This is not allowed in for-of loops.

信息

¥Message

SyntaxError: for-of loop variable declaration may not have an initializer. (V8-based)
SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)
SyntaxError: Cannot assign to the loop variable inside a for-of loop header. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

for...of 循环的头部包含一个初始化表达式。即,声明一个变量并为其赋予值 for (const i = 0 of iterable)。这在 for-of 循环中是不允许的。你可能需要一个允许初始化程序的 for 循环。

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

示例

¥Examples

无效的 for-of 循环

¥Invalid for-of loop

js
const iterable = [10, 20, 30];

for (const value = 50 of iterable) {
  console.log(value);
}

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

有效的 for-of 循环

¥Valid for-of loop

你需要删除 for-of 循环头部的初始化程序 (value = 50)。例如,也许你打算将 50 设置为偏移值,在这种情况下你可以将其添加到循环体中。

¥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.

js
const iterable = [10, 20, 30];

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

也可以看看

¥See also