no-sparse-arrays
不允许稀疏数组
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
稀疏数组包含空槽,最常见的原因是数组字面中使用了多个逗号,例如:
¥Sparse arrays contain empty slots, most frequently due to multiple commas being used in an array literal, such as:
var items = [,,];
虽然此示例中的 items
数组的 length
为 2,但实际上 items[0]
或 items[1]
中没有值。数组字面量仅在内部使用逗号是有效的,再加上设置了 length
而未设置实际项目值,这使得稀疏数组对许多开发者感到困惑。考虑以下:
¥While the items
array in this example has a length
of 2, there are actually no values in items[0]
or items[1]
. The fact that the array literal is valid with only commas inside, coupled with the length
being set and actual item values not being set, make sparse arrays confusing for many developers. Consider the following:
var colors = [ "red",, "blue" ];
在此示例中,colors
数组的 length
为 3。但开发者是否打算在数组中间留出一个空位?还是打错了?
¥In this example, the colors
array has a length
of 3. But did the developer intend for there to be an empty spot in the middle of the array? Or is it a typo?
以这种方式定义的稀疏数组引起的混乱足以建议避免使用它们,除非你确定它们在你的代码中有用。
¥The confusion around sparse arrays defined in this manner is enough that it’s recommended to avoid using them unless you are certain that they are useful in your code.
规则详情
¥Rule Details
此规则不允许具有 “holes” 的稀疏数组字面,其中逗号前面没有元素。它不适用于最后一个元素后面的逗号。
¥This rule disallows sparse array literals which have “holes” where commas are not preceded by elements. It does not apply to a trailing comma following the last element.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-sparse-arrays: "error"*/
var items = [,];
var colors = [ "red",, "blue" ];
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-sparse-arrays: "error"*/
var items = [];
var items = new Array(23);
// trailing comma (after the last element) is not a problem
var colors = [ "red", "blue", ];
何时不使用
¥When Not To Use It
如果你想使用稀疏数组,那么禁用这个规则是安全的。
¥If you want to use sparse arrays, then it is safe to disable this rule.
版本
此规则是在 ESLint v0.4.0 中引入。