Skip to content

JavaScript 中判断是否为数组 ​

2023-06-19 16:54:14

isArray ​

最稳定可靠的方法,直接调用 ES6 的 Array.isArray(),返回一个布尔值

instanceOf ​

instanceOf 运算符用于检验构造函数的 prototype 属性是否出现在对象的原型链中的任何位置,返回一个布尔值

ts
const a = []
a instanceOf Array

constructor ​

实例的构造函数属性 constructor 指向构造函数,那么通过 constructor 属性也可以判断是否为一个数组

ts
const a = []
a.constructor === Array

Object.prototype.toString.call() ​

通过这个方法不仅可以判断对象,函数也可以进行判断

ts
const a = []
Object.prototype.toString.call(a) === '[object Array]'

Released under the MIT License.