语法错误:相等测试 (==) 被错误地输入为赋值 (=)?
当你通常期望进行相等性测试 (==
) 时进行赋值 (=
) 时,就会出现 JavaScript 警告 "相等测试 (==) 被错误地输入为赋值 (=)?"。
¥The JavaScript warning "test for equality (==) mistyped as assignment (=)?" occurs when
there was an assignment (=
) when you would normally expect a test for
equality (==
).
信息
错误类型
¥Error type
(仅限 Firefox)仅当 javascript.options.strict
首选项设置为 true
时才会报告 SyntaxError
警告。
¥(Firefox only) SyntaxError
warning which is reported only if
javascript.options.strict
preference is set to true
.
什么地方出了错?
示例
条件表达式内的赋值
¥Assignment within conditional expressions
建议不要在条件表达式中使用简单的赋值(例如 if...else
),因为浏览代码时赋值可能会与相等相混淆。例如,请勿使用以下代码:
¥It is advisable to not use simple assignments in a conditional expression (such as
if...else
),
because the assignment can be confused with equality when glancing over the code. For
example, do not use the following code:
if (x = y) {
// do the right thing
}
如果需要在条件表达式中使用赋值,常见的做法是在赋值周围添加额外的括号。例如:
¥If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if ((x = y)) {
// do the right thing
}
否则,你可能打算使用比较运算符(例如 ==
或 ===
):
¥Otherwise, you probably meant to use a comparison operator (e.g. ==
or
===
):
if (x === y) {
// do the right thing
}