no-array-constructor
禁止 Array 构造函数
一般不推荐使用 Array 构造函数来构造新数组,而更推荐使用数组字面量表示法,这是因为单参数陷阱以及 Array 全局对象可能被重新定义。例外情况是当使用 Array 构造函数通过给构造函数一个单一的数字参数来有意创建指定大小的稀疏数组时。
🌐 Use of the Array constructor to construct a new array is generally
discouraged in favor of array literal notation because of the single-argument
pitfall and because the Array global may be redefined. The exception is when
the Array constructor is used to intentionally create sparse arrays of a
specified size by giving the constructor a single numeric argument.
规则详情
🌐 Rule Details
此规则不允许使用 Array 构造函数。
🌐 This rule disallows Array constructors.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-array-constructor: "error"*/
Array();
Array(0, 1, 2);
new Array(0, 1, 2);
Array(...args);
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-array-constructor: "error"*/
Array(500);
new Array(someOtherArray.length);
[0, 1, 2];
const createArray = Array => new Array();
此规则还支持 TypeScript 类型语法。
🌐 This rule additionally supports TypeScript type syntax.
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-array-constructor: "error"*/
new Array<number>(1, 2, 3);
new Array<Foo>();
Array<number>(1, 2, 3);
Array<Foo>();
Array?.foo();
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-array-constructor: "error"*/
new Array();
new Array(0, 1, 2);
Array?.(x, y);
Array?.(0, 1, 2);
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
何时不使用
🌐 When Not To Use It
这个规则强制执行几乎普遍的风格问题。话虽如此,如果更喜欢构造函数样式,可以禁用此规则。
🌐 This rule enforces a nearly universal stylistic concern. That being said, this rule may be disabled if the constructor style is preferred.
相关规则
版本
此规则是在 ESLint v0.4.0 中引入。