Skip to content

如何判断一个对象是否是数组

解析

  • 通过 Object.prototype.toString
ts
const isArray = (obj) => {
  return Object.prototype.toString.call(obj) === '[object Array]'
}

// 缺点, 以下模式会是Array
var obj = {
  [Symbol.toStringTag]: 'Array'
}
  • 通过instanceof
ts
const isArray = (obj) => {
  return obj instanceof Array;
}

// 缺点,强制修改了obj的原型链
var obj = {};
Object.setPrototypeOf(obj, Array.prototype);
  • 通过Array.isArray
ts
const isArray = (obj) => Array.isArray(obj)