uTools-Manuals/docs/javascript/Reference/Errors/Invalid_for-of_initializer.html
2019-04-21 11:50:48 +08:00

40 lines
2.4 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<article id="wikiArticle">
<div></div>
<h2 id="错误信息">错误信息</h2>
<pre><code class="language-javascript">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)
</code></pre>
<h2 id="错误类型">错误类型</h2>
<p><a href="Reference/Global_Objects/SyntaxError" title="SyntaxError 对象代表尝试解析语法上不合法的代码的错误。"><code>SyntaxError</code></a></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><code class="language-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</code></pre>
<h3 id="合法的_for-of_循环形式">合法的 <code>for-of</code> 循环形式</h3>
<p>需要将初始化器 (<code>value = 50</code>) 从<code>for-of</code> 循环的头部移除。或许你的本意是给每个值添加 50 的偏移量,在这种情况下,可以在循环体中进行添加。</p>
<pre><code class="language-js example-good">let iterable = [10, 20, 30];
for (let value of iterable) {
value += 50;
console.log(value);
}
// 60
// 70
// 80
</code></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>
</article>