Skip to content
← Back to rules

unicorn/prefer-at 严谨

⚠️🛠️ A dangerous auto-fix is available for this rule.

它做了什么

优先使用 .at() 方法进行索引访问,以及使用 String#charAt()

为什么这是不好的?

.at() 方法在通过索引访问元素时更具可读性和一致性,尤其是在使用负索引(从末尾开始访问元素)时。

示例

此规则的错误代码示例:

js
const foo = array[array.length - 1];
const foo = array.slice(-1)[0];
const foo = string.charAt(string.length - 1);

此规则的正确代码示例:

js
const foo = array.at(-1);
const foo = array.at(-5);
const foo = string.at(-1);

配置

此规则接受一个配置对象,包含以下属性:

checkAllIndexAccess

type: boolean

default: false

检查所有索引访问,而不仅仅是像 array.length - 1 这样的特殊模式。 启用后,array[0]array[1] 等也会被标记。

getLastElementFunctions

type: string[]

default: []

将函数名列表视为“获取最后一个元素”的函数。 这些函数将被检查是否使用了 .at(-1)

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "unicorn/prefer-at": "error"
  }
}
bash
oxlint --deny unicorn/prefer-at

参考资料