no-self-assign

禁止双方完全相同的分配

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

自分配没有效果,因此可能是由于重构不完整而导致的错误。那些表明你应该做的事情仍然存在。

¥Self assignments have no effect, so probably those are an error due to incomplete refactoring. Those indicate that what you should do is still remaining.

foo = foo;
[bar, baz] = [bar, qiz];

规则详情

¥Rule Details

该规则旨在消除自我分配。

¥This rule is aimed at eliminating self assignments.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-self-assign: "error"*/

foo = foo;

[a, b] = [a, b];

[a, ...b] = [x, ...b];

({a, b} = {a, x});

foo &&= foo;
foo ||= foo;
foo ??= foo;

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-self-assign: "error"*/

foo = bar;
[a, b] = [b, a];

// This pattern is warned by the `no-use-before-define` rule.
let foo = foo;

// The default values have an effect.
[foo = 1] = [foo];

// non-self-assignments with properties.
obj.a = obj.b;
obj.a.b = obj.c.b;
obj.a.b = obj.a.c;
obj[a] = obj["a"];

// This ignores if there is a function call.
obj.a().b = obj.a().b;
a().b = a().b;

// `&=` and `|=` have an effect on non-integers.
foo &= foo;
foo |= foo;

// Known limitation: this does not support computed properties except single literal or single identifier.
obj[a + b] = obj[a + b];
obj["a" + "b"] = obj["a" + "b"];

选项

¥Options

此规则还可以选择检查属性。

¥This rule has the option to check properties as well.

{
    "no-self-assign": ["error", {"props": true}]
}
  • props - 如果这是 trueno-self-assign 规则警告属性的自我分配。默认为 true

    ¥props - if this is true, no-self-assign rule warns self-assignments of properties. Default is true.

props

使用 { "props": false } 选项的正确代码示例:

¥Examples of correct code with the { "props": false } option:

在线运行
/*eslint no-self-assign: ["error", {"props": false}]*/

// self-assignments with properties.
obj.a = obj.a;
obj.a.b = obj.a.b;
obj["a"] = obj["a"];
obj[a] = obj[a];

何时不使用

¥When Not To Use It

如果你不想通知自我分配,那么禁用此规则是安全的。

¥If you don’t want to notify about self assignments, then it’s safe to disable this rule.

版本

此规则是在 ESLint v2.0.0-rc.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号