SyntaxError: for-in loop head declarations may not have initializers - JavaScript 编辑

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-of loops in strict mode.

Message

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

Error type

SyntaxError in strict mode only.

What went wrong?

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.

Examples

This example throws a 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

Valid for-in loop

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

"use strict";

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

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

Array iteration

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:

var arr = [ "a", "b", "c" ]

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

// "c"

See also

  • for...in
  • for...of – also disallows an initializer in both strict and non-strict mode.
  • for – preferred for array iteration, allows to define an initializer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:98 次

字数:3841

最后编辑:6 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文