在线文档教程
JavaScript
错误 | Errors

Errors: Invalid for-in initializer

Errors: Invalid for-in initializer

信息

SyntaxError: for-in loop head declarations may not have initializers (Firefox) SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome)

错误类型

SyntaxError in strict mode only.

什么地方出了错?

for ... in循环的头部包含一个初始化表达式。也就是说,一个变量被声明并赋值为| for (var i = 0 in obj)|。在非严格模式下,这个头部声明默默无视,行为如此|for (var i in obj)|。然而在严格的模式下,a SyntaxError被抛出。

例子

这个例子抛出SyntaxError

"use strict"; var obj = {a: 1, b: 2, c: 3 }; for (var i = 0 in obj) { console.log(obj[i] } // SyntaxError: for-in loop head declarations may not have initializers

有效的for-in循环

你可以去掉i = 0for-in循环头部的initializer()。

"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循环允许您设置一个初始值,然后还有:

var arr = [ "a", "b", "c" ] for (var i = 2; i < arr.length; i++) { console.log(arr[i] } // "c"