Check if a value is array type in Javascript
![Check if a value is array type in Javascript](/content/images/size/w2000/2021/01/javascript-736400.png)
Check if a value is an array type.
To check whether an object is array type, use Array.isArray(), instead of instanceof Array
. Reason: instanceof Array
does not work across realms ( window
, iframe
). Check here, and here.
![](https://transang.me/content/images/2020/09/image-9.png)
![](https://transang.me/content/images/2020/09/image-10.png)
Note that a TypedArray (e.g., new Int8Array(8)
, ...) gives a false
result when passed in Array.isArray()
.
Array.isArray
check if a value is array type by looking at the value's constructor name. It is implemented in corejs as:
Array.isArray = value => Object.prototype.toString.call(value) === '[object Array]'
corejs source: here and here.
Nonetheless, please keep in mind that this implementation is best-effort to mimic the behavior, and does not perfectly satisfy the requirements specified by the ECMA specs.
const a = {}
a[Symbol.toStringTag] = 'Array'
console.log(Array.isArray(a)) // print false
delete Array.isArray
require("core-js/modules/es.array.is-array")
console.log(Array.isArray(a)) // print true
![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/v2/default-red.png)