语法错误: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)
错误类型
什么地方出了错?
¥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
.
示例
有效的 for-in 循环
数组迭代
¥Array iteration
for...in 循环 不应该用于数组迭代。你是否打算使用 for
循环而不是 for-in
循环来迭代 Array
?for
循环也允许你设置一个初始值设定项:
¥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:
const arr = ["a", "b", "c"];
for (let i = 2; i < arr.length; i++) {
console.log(arr[i]);
}
// "c"