no-cond-assign
禁止在条件表达式中使用赋值运算符
✅ 推荐
使用 recommended 配置从 @eslint/js 在 配置文件 中启用此规则
在条件语句中,很容易将比较运算符(例如 ==)误写成赋值运算符(例如 =)。例如
// 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" 选项时,此规则的 错误 代码示例
在 Playground 中打开
/*eslint no-cond-assign: "error"*/
// Unintentional assignment
let x;
if () {
const b = 1;
}
// Practical example that is similar to an error
const setHeight = function (someNode) {
do {
someNode.height = "100px";
} while ();
}
使用默认 "except-parens" 选项时,此规则的 正确 代码示例
在 Playground 中打开
/*eslint no-cond-assign: "error"*/
// Assignment replaced by comparison
let x;
if (x === 0) {
const b = 1;
}
// Practical example that wraps the assignment in parentheses
const setHeight = function (someNode) {
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode));
}
// Practical example that wraps the assignment and tests for 'null'
const set_height = function (someNode) {
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode) !== null);
}
always
使用 "always" 选项时,此规则的 错误 代码示例
在 Playground 中打开
/*eslint no-cond-assign: ["error", "always"]*/
// Unintentional assignment
let x;
if () {
const b = 1;
}
// Practical example that is similar to an error
const setHeight = function (someNode) {
do {
someNode.height = "100px";
} while ();
}
// Practical example that wraps the assignment in parentheses
const set_height = function (someNode) {
do {
someNode.height = "100px";
} while (());
}
// Practical example that wraps the assignment and tests for 'null'
const heightSetter = function (someNode) {
do {
someNode.height = "100px";
} while (() !== null);
}
使用 "always" 选项时,此规则的 正确 代码示例
在 Playground 中打开
/*eslint no-cond-assign: ["error", "always"]*/
// Assignment replaced by comparison
let x;
if (x === 0) {
const b = 1;
}
相关规则
版本
此规则是在 ESLint v0.0.9 中引入的。