语法错误:for-in 循环头声明可能没有初始值设定项

for...in 的头部包含初始化表达式(例如 for (var i = 0 in obj))时,会发生 JavaScript 严格模式-only 异常 "for-in 循环头声明可能没有初始值设定项"。在严格模式下的 for-in 循环中不允许这样做。此外,在严格模式之外也不允许使用像 for (const i = 0 in obj) 这样的初始化器的词法声明。

¥The JavaScript strict mode-only exception "for-in loop head declarations may not have initializers" occurs when the head of a for...in contains an initializer expression, such as for (var i = 0 in obj). This is not allowed in for-in loops in strict mode. In addition, lexical declarations with initializers like for (const i = 0 in obj) are not allowed outside strict mode either.

信息

¥Message

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

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

for...in 循环的头部包含一个初始化表达式。即,声明一个变量并为其赋予值 for (var i = 0 in obj)。在非严格模式下,该头声明会被默默忽略,其行为类似于 for (var i in obj)。然而,在 严格模式 中,抛出了 SyntaxError。此外,在严格模式之外也不允许使用像 for (const i = 0 in obj) 这样的初始值设定项的词法声明,并且始终会生成 SyntaxError

¥The head of a for...in loop contains an initializer expression. That is, a variable is declared and assigned a value for (var i = 0 in obj). In non-strict mode, this head declaration is silently ignored and behaves like for (var i in obj). In strict mode, however, a SyntaxError is thrown. In addition, lexical declarations with initializers like for (const i = 0 in obj) are not allowed outside strict mode either, and will always produce a SyntaxError.

示例

¥Examples

此示例抛出 SyntaxError

¥This example throws a SyntaxError:

js
const obj = { a: 1, b: 2, c: 3 };

for (const i = 0 in obj) {
  console.log(obj[i]);
}

// SyntaxError: for-in loop head declarations may not have initializers

有效的 for-in 循环

¥Valid for-in loop

你可以删除 for-in 循环头部的初始化程序 (i = 0)。

¥You can remove the initializer (i = 0) in the head of the for-in loop.

js
const obj = { a: 1, b: 2, c: 3 };

for (const i in obj) {
  console.log(obj[i]);
}

数组迭代

¥Array iteration

for...in 循环 不应该用于数组迭代。你是否打算使用 for 循环而不是 for-in 循环来迭代 Arrayfor 循环也允许你设置一个初始值设定项:

¥The for...in loop shouldn't be used for Array iteration. Did you intend to use a for loop instead of a for-in loop to iterate an Array? The for loop allows you to set an initializer then as well:

js
const arr = ["a", "b", "c"];

for (let i = 2; i < arr.length; i++) {
  console.log(arr[i]);
}

// "c"

也可以看看

¥See also