如何判断一个元素是数组?
- 通过Object.prototype.toString.call()做判断
Object.prototype.toString.call([]).slice(8,-1) === 'Array';
- 通过原型链做判断
let a = []
var b = {}
a.__proto__ === Array.prototype; // true
b.__proto__ === Array.prototype; // false
- 通过ES6的
Array.isArray()做判断
let a = []
var b = {}
Array.isArray(a) // true
Array.isArray(b) // false
- 通过instanceof做判断
let a = []
var b = {}
a instanceof Array // true
b instanceof Array // false
- 通过
Array.prototype.isPrototypeOf
let a = []
var b = {}
Array.prototype.isPrototypeOf(a) // true
Array.prototype.isPrototypeOf(b) // false
备注: isPrototypeOf() 与 instanceof 运算符不同。在表达式 "object instanceof AFunction"中,object 的原型链是针对 AFunction.prototype 进行检查的,而不是针对 AFunction 本身。