一、判断一个对象是否是数组?
var obj1={x:1}, obj2=[1,2], obj3=new Date();
1.判断当前对象的原型对象是否是数组的原型对象
//1.使用__proto__获得对象的原型对象
obj1.__proto__==Array.prototype;//false
obj2.__proto__==Array.prototype;//true
obj3.__proto__==Array.prototype;//false
//2.因为__proto__可能被浏览器禁用,所以可用Object.getPrototypeOf()
Object.getPrototypeOf(obj1)==Array.prototype;//false
Object.getPrototypeOf(obj2)==Array.prototype;//true
Object.getPrototypeOf(obj3)==Array.prototype;//false
//3.更直接的函数father.isPrototypeOf(child)
Array.prototype.isPrototypeOf(obj1);//false
Array.prototype.isPrototypeOf(obj2);//true
Array.prototype.isPrototypeOf(obj3);//false
2.判断当前对象的构造函数是否是Array
//1.判断原型对象中的constructor属性(对象自己没有,会去原型对象上查找)
obj1.constructor==Array;//false
obj2.constructor==Array;//true
obj3.constructor==Array;//false
//2.用instanceOf方法判断对象是否是Array的示例
obj1 instanceOf Array;//false
obj2 instanceOf Array;//false
obj3 instanceOf Array;//false
但是上面这些方法有局限性,如果手动修改了对象的原型对象,那么这些方法就判断不了了
3.使用Object原型对象中的toString()方法
//但是数组和日期对象的原型对象中有自己的toString方法,所以要用call方法
Object.prototype.toString.call(obj1);//[object Object]
Object.prototype.toString.call(obj2);//[object Array]
Object.prototype.toString.call(obj3);//[object Date]
4.使用ES5的isArray方法
Array.isArray(obj1);//false
Array.isArray(obj2);//true
Array.isArray(obj3);//false