Skip to content
← Back to rules

unicorn/no-immediate-mutation Pedantic

🚧 An auto-fix is planned for this rule, but not implemented at this time.

它的作用

禁止在变量初始化后立即修改该变量。

为什么这不好?

当你初始化一个变量后又立即修改它时,最好直接在初始化时包含 这个修改。这样可以使代码更易读,并减少 语句数量。

示例

以下是此规则的错误代码示例:

js
const array = [1, 2];
array.push(3);

const object = { foo: 1 };
object.bar = 2;

const set = new Set([1, 2]);
set.add(3);

const map = new Map([["foo", 1]]);
map.set("bar", 2);

以下是此规则的正确代码示例:

js
const array = [1, 2, 3];

const object = { foo: 1, bar: 2 };

const set = new Set([1, 2, 3]);

const map = new Map([
  ["foo", 1],
  ["bar", 2],
]);

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/no-immediate-mutation": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/no-immediate-mutation": "error",
  },
});
bash
oxlint --deny unicorn/no-immediate-mutation

版本

此规则在 v1.35.0 中添加。

参考资料