# no-cond-assign
禁止条件表达式中的赋值运算符
配置文件中的 "extends": "eslint:recommended" 属性启用了该规则
在条件语句中,很容易将比较运算符(例如 ==
)误键入为赋值运算符(例如 =
)。例如:
// Check the user's job title
if (user.jobTitle = "manager") {
// user.jobTitle is now incorrect
}
在条件语句中使用赋值运算符是有充分理由的。然而,很难判断一个特定的任务是否是故意的。
# 规则详情
此规则不允许在 if
、for
、while
和 do...while
语句的测试条件中使用模棱两可的赋值运算符。
# 选项
此规则有一个字符串选项:
"except-parens"
(默认)仅在括号括起来时才允许在测试条件中赋值(例如,允许在while
或do...while
循环的测试中重新分配变量)"always"
不允许在测试条件下进行所有分配
# except-parens
此规则使用默认 "except-parens"
选项的错误代码示例:
/*eslint no-cond-assign: "error"*/
// Unintentional assignment
var x;
if (x = 0) {
var b = 1;
}
// Practical example that is similar to an error
function setHeight(someNode) {
"use strict";
do {
someNode.height = "100px";
} while (someNode = someNode.parentNode);
}
此规则使用默认 "except-parens"
选项的正确代码示例:
/*eslint no-cond-assign: "error"*/
// Assignment replaced by comparison
var x;
if (x === 0) {
var b = 1;
}
// Practical example that wraps the assignment in parentheses
function setHeight(someNode) {
"use strict";
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode));
}
// Practical example that wraps the assignment and tests for 'null'
function setHeight(someNode) {
"use strict";
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode) !== null);
}
# always
此规则使用 "always"
选项的错误代码示例:
/*eslint no-cond-assign: ["error", "always"]*/
// Unintentional assignment
var x;
if (x = 0) {
var b = 1;
}
// Practical example that is similar to an error
function setHeight(someNode) {
"use strict";
do {
someNode.height = "100px";
} while (someNode = someNode.parentNode);
}
// Practical example that wraps the assignment in parentheses
function setHeight(someNode) {
"use strict";
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode));
}
// Practical example that wraps the assignment and tests for 'null'
function setHeight(someNode) {
"use strict";
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode) !== null);
}
此规则使用 "always"
选项的正确代码示例:
/*eslint no-cond-assign: ["error", "always"]*/
// Assignment replaced by comparison
var x;
if (x === 0) {
var b = 1;
}