Skip to content
← Back to rules

unicorn/prefer-negative-index Style

🛠️ An auto-fix is available for this rule.

作用

在可能的情况下,优先使用负索引而不是 .length - index

为什么这不好?

atslice 中使用负索引通常比使用 .length - index 更易读 也更简洁。

示例

此规则的错误代码示例:

js
foo.slice(foo.length - 2, foo.length - 1);
foo.at(foo.length - 1);

此规则的正确代码示例:

js
foo.slice(-2, -1);
foo.at(-1);

如何使用

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

json
{
  "rules": {
    "unicorn/prefer-negative-index": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-negative-index": "error",
  },
});
bash
oxlint --deny unicorn/prefer-negative-index

版本

此规则于 v0.13.2 中添加。

参考