Skip to content
← Back to rules

unicorn/no-new-array Correctness

✅ This rule is turned on by default.
⚠️ 💡 A dangerous suggestion is available for this rule.

作用 ​

禁止使用 new Array()。

为什么这不好? ​

当使用 Array 构造函数并传入一个参数时,不清楚该参数是表示数组的长度,还是表示唯一的元素。

示例 ​

此规则的错误代码示例:

javascript
const array = new Array(1);
const array = new Array(42);
const array = new Array(foo);

此规则的正确代码示例:

javascript
const array = Array.from({ length: 42 });
const array = [42];

如何使用 ​

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

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

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

版本 ​

此规则添加于 v0.0.16。

参考资料 ​