useIsArray
诊断类别:lint/suspicious/useIsArray
¥Diagnostic Category: lint/suspicious/useIsArray
自从:v1.0.0
¥Since: v1.0.0
来源:
¥Sources:
-
与以下相同:
unicorn/no-instanceof-array
¥Same as:
unicorn/no-instanceof-array
使用 Array.isArray()
而不是 instanceof Array
。
¥Use Array.isArray()
instead of instanceof Array
.
在 JavaScript 中,一些类似数组的对象(例如参数)不是 Array
类的实例。/// Moreover, the global Array
class can be different between two execution contexts.例如,Web 浏览器中的两个框架具有不同的 Array
类。在这些上下文之间传递数组会导致数组不是上下文全局 Array
类的实例。为了避免这些问题,请使用 Array.isArray()
而不是 instanceof Array
。有关更多详细信息,请参阅 MDN 文档。
¥In JavaScript some array-like objects such as arguments are not instances of the Array
class. ///
Moreover, the global Array
class can be different between two execution contexts.
For instance, two frames in a web browser have a distinct Array
class.
Passing arrays across these contexts, results in arrays that are not instances of the contextual global Array
class.
To avoid these issues, use Array.isArray()
instead of instanceof Array
.
See the MDN docs for more details.
¥Examples
¥Invalid
code-block.js:2:5 lint/suspicious/useIsArray FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Use Array.isArray() instead of instanceof Array.
1 │ const xs = [];
> 2 │ if (xs instanceof Array) {}
│ ^^^^^^^^^^^^^^^^^^^
3 │
ℹ instanceof Array returns false for array-like objects and arrays from other execution contexts.
ℹ Unsafe fix: Use Array.isArray() instead.
1 1 │ const xs = [];
2 │ - if·(xs·instanceof·Array)·{}
2 │ + if·(Array.isArray(xs))·{}
3 3 │
¥Valid
¥Related links