aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.html
blob: e92f0a63e8429c00de9c4b4099b544b738d8d1d4 (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
---
title: 'SyntaxError: test for equality (==) mistyped as assignment (=)?'
slug: Web/JavaScript/Reference/Errors/Equal_as_assign
tags:
  - 语法错误
translation_of: Web/JavaScript/Reference/Errors/Equal_as_assign
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="消息">消息</h2>

<pre class="syntaxbox">Warning: SyntaxError: test for equality (==) mistyped as assignment (=)?
</pre>

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

<p>{{jsxref("SyntaxError")}} 只在<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">严格模式</a>下会出现的警告。</p>

<h2 id="什么地方出错了">什么地方出错了?</h2>

<p>在通常期望进行相等判定(<code>==</code>)的地方出现了赋值<code>(=</code>)。 为了帮助调试,JavaScript(在开启严格模式的情况下)会对这种情况进行警告。</p>

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

<h3 id="条件表达式内的赋值">条件表达式内的赋值</h3>

<p>不建议在条件表达式中 (例如 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if...else</a></code>) 使用简单赋值语句,因为在扫视代码的时候赋值操作与相等判定容易产生混淆。例如,不要使用以下写法:</p>

<pre class="brush: js example-bad">if (x = y) {
  // do the right thing
}
</pre>

<p>如果你需要在条件表达式中使用赋值语句, 通常的做法是用一对括号把赋值语句包起来。 例如:</p>

<pre class="brush: js">if ((x = y)) {
  // do the right thing
}</pre>

<p>否则, 你的本意可能是想用比较操作符 (如 <code>==</code><code>===</code>):</p>

<pre class="brush: js">if (x == y) {
  // do the right thing
}</pre>

<h2 id="相关页面">相关页面</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if...else</a></code></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">Comparison operators</a></li>
</ul>