如何判断一个对象是否是数组
解析
- 通过
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)