最近两次面试都被问到了判断数组的方法,以此来记录一下
1、instanceof
instanceof可以用来判断引用数据类型,那么当然可以判断数组啦
arr = [];
arr instanceof Array // true
2、constructor
通过constructor属性查看当前变量的构造函数是否为Array来判断是否为数组
arr = [];
arr.constructor === Array //true
3、proto
判断当前变量的__proto__属性和Array的原型的指向是否相同
arr = []
arr.__proto__ === Array.prototype // true
4、Object.prototype.toString.call
虽然Array也继承了Object上的方法,但是原型上重写了toString方法
arr = []
Object.prototype.toString.call(arr).slice(8,-1)=== 'Array' // true
5、isArray
ES5中新增的方法
arr = []
isArray(arr) // true
6、isPrototypeOf
isPrototypeOf()方法用来判断一个对象是否在另一个对象的原型链上,因为arr的原型(__proto__)在Array的原型(prototype)上,所以返回true
arr = []
Arr.prototype.isPrototype(arr) // true
7、Object.getPrototypeOf
Object.getPrototypeOf()方法返回指定对象的原型
arr = [];
Object.getPrototypeOf(arr) === Array.prototype // true