SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript 编辑

The JavaScript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a for...of loop contains an initializer expression such as |for (var i = 0 of iterable)|. This is not allowed in for-of loops.

Message

SyntaxError: for-of loop head declarations cannot have an initializer (Edge)
SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)
SyntaxError: for-of loop variable declaration may not have an initializer. (Chrome)

Error type

SyntaxError

What went wrong?

The head of a for...of loop contains an initializer expression. That is, a variable is declared and assigned a value |for (var i = 0 of iterable)|. This is not allowed in for-of loops. You might want a for loop that does allow an initializer.

Examples

Invalid for-of loop

let iterable = [10, 20, 30];

for (let value = 50 of iterable) {
  console.log(value);
}

// SyntaxError: a declaration in the head of a for-of loop can't
// have an initializer

Valid for-of loop

You need to remove the initializer (value = 50) in the head of the for-of loop. Maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example.

let iterable = [10, 20, 30];

for (let value of iterable) {
  value += 50;
  console.log(value);
}
// 60
// 70
// 80

See also

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

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

发布评论

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

词条统计

浏览:76 次

字数:3144

最后编辑:6 年前

编辑次数:0 次

更多

友情链接

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