no-self-assign
禁止自身赋值,即赋值语句左右两边完全相同
✅ 推荐
在配置文件中使用 @eslint/js
的 recommended
配置启用此规则
自身赋值没有效果,所以很可能是由于不完整的重构而导致的错误。这表明您应该做的事情仍然存在。
foo = foo;
[bar, baz] = [bar, qiz];
规则详情
此规则旨在消除自身赋值。
错误代码示例(针对此规则)
在 Playground 中打开
/*eslint no-self-assign: "error"*/
foo = ;
[a, b] = [, ];
[a, ...b] = [x, ...];
({a, b} = {, x});
foo &&= ;
foo ||= ;
foo ??= ;
正确代码示例(针对此规则)
在 Playground 中打开
/*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"];
选项
此规则可以选择也检查属性。
{
"no-self-assign": ["error", {"props": true}]
}
props
- 如果为true
,no-self-assign
规则会警告属性的自身赋值。默认为true
。
props
使用 { "props": false }
选项的正确代码示例
在 Playground 中打开
/*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];
何时不使用
如果您不想收到关于自身赋值的通知,那么禁用此规则是安全的。
版本
此规则在 ESLint v2.0.0-rc.0 中引入。