SyntaxError: for-in 循环头部声明不能有初始化器
当 for...in 的头部包含初始化表达式(例如 for (var i = 0 in obj)
)时,就会发生仅限严格模式的 JavaScript 严格模式 异常“for-in 循环头部声明不能有初始化程序”。在严格模式下,for-in 循环中不允许这样做。此外,在严格模式之外也不允许使用带有初始化程序的词法声明,例如 for (const i = 0 in obj)
。
消息
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)
错误类型
哪里出错了?
示例
此示例会抛出 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 循环
您可以删除 for-in 循环头部中的初始化程序 (i = 0
)。
js
const obj = { a: 1, b: 2, c: 3 };
for (const i in obj) {
console.log(obj[i]);
}
数组迭代
for...in 循环不应用于数组迭代。您是否打算使用 for
循环而不是 for-in
循环来迭代 Array
?for
循环也允许您设置初始化程序。
js
const arr = ["a", "b", "c"];
for (let i = 2; i < arr.length; i++) {
console.log(arr[i]);
}
// "c"