SyntaxError: for-in loop head declarations may not have initializers
错误提示
SyntaxError: for-in loop head declarations may not have initializers (Firefox) SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome)
错误类型
该 SyntaxError
只出现于严格模式下。
哪里出错了?
示例
下面这个示例会报语法错误(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 循环
可以把初始化语句 (i = 0
) 从 for-in 循环的头部移除。
js
"use strict";
var obj = { a: 1, b: 2, c: 3 };
for (var i in obj) {
console.log(obj[i]);
}
数组迭代
for...in 循环不应该应用于数组迭代中。是否考虑使用 for
循环而不是 for-in
循环来遍历数组(Array
)?在 for 循环中是允许使用初始化语句的:
js
var arr = ["a", "b", "c"];
for (var i = 2; i < arr.length; i++) {
console.log(arr[i]);
}
// "c"