aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/errors/invalid_for-of_initializer/index.html
blob: 7e93d3af35474d091e9ef6c5034dad0a5183c5f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
---
title: >-
  SyntaxError: a declaration in the head of a for-of loop can't have an
  initializer
slug: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer
tags:
  - JavaScript
  - 语法错误
  - 错误提示
translation_of: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="错误信息">错误信息</h2>

<pre class="syntaxbox">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)
</pre>

<h2 id="错误类型">错误类型</h2>

<p>{{jsxref("SyntaxError")}}</p>

<h2 id="哪里出错了?">哪里出错了?</h2>

<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> 循环的头部包含有初始化表达式。也就是对一个变量进行声明并赋值|<code>for (var i = 0 of iterable)</code>|。这在 for-of 循环中是被禁止的。你想要的可能是允许包含初始化器的 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> 循环形式。</p>

<h2 id="示例">示例</h2>

<h3 id="非法的_for-of_循环形式">非法的 <code>for-of</code> 循环形式</h3>

<pre class="brush: js example-bad">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</pre>

<h3 id="合法的_for-of_循环形式">合法的 <code>for-of</code> 循环形式</h3>

<p>需要将初始化器 (<code>value = 50</code>) 从<code>for-of</code> 循环的头部移除。或许你的本意是给每个值添加 50 的偏移量,在这种情况下,可以在循环体中进行添加。</p>

<pre class="brush: js example-good">let iterable = [10, 20, 30];

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

<h2 id="相关内容">相关内容</h2>

<ul>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code></li>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code> – 在严格模式下也同样禁止使用初始化器 (<a href="/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer">SyntaxError: for-in loop head declarations may not have initializers</a>)</li>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> – 在迭代时允许定义初始化器</li>
</ul>