no-cond-assign

配置文件中的"extends": "eslint:recommended"属性启用此规则。

在条件语句中,将比较运算符(如==)作为赋值运算符(例如=)输错是非常容易的。例如:

// Check the user's job title
if (user.jobTitle = "manager") {
    // user.jobTitle is now incorrect
}

在条件语句中使用赋值运算符是有正当理由的。但是,可能很难判断具体的任务是否是故意的。

规则细节

这条规则不允许在试验条件不明确赋值运算符ifforwhile,和do...while语句。

选项

这条规则有一个字符串选项:

  • "except-parens"(缺省值)只允许在测试条件下进行赋值,如果它们被括在圆括号中(例如,允许在whiledo...while循环的测试中重新赋值变量)
  • "always" 不允许在测试条件下的所有分配

除了-双亲

此规则的默认"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"选项的此规则的错误代码示例:

/*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;
}

相关规则

  • no-extra-parensVersion 这个规则是在 ESLint 0.0.9.Resources 中引入的

扫码关注云+社区

领取腾讯云代金券