判断一个对象是否是数组类型的几种方法
-----判断一个类型是不是数组一共有8种方法,如下:
var obj1={},obj2=[1,2,3],obj3=new Date();
1.通过此对象的爹判断是不是数组的原型对象
console.log(//通过此对象的爹判断是不是数组的原型对象
obj1.proto==Array.prototype,
obj2.proto==Array.prototype,//true 为数组
obj3.proto==Array.prototype
)
2.判断obj的原型对象是不是数组的原型对象
console.log(// ,obj的原型对象是不是数组的原型对象
Object.getPrototypeOf(obj1)==Array.prototype,
Object.getPrototypeOf(obj2)==Array.prototype,
Object.getPrototypeOf(obj3)==Array.prototype
)
//3.一个更直接函数 father.isPrototypeOf(child)
console.log(//数组的原型对象是obj的原型对象吗?
Array.prototype.isPrototypeOf(obj1),
Array.prototype.isPrototypeOf(obj2),
Array.prototype.isPrototypeOf(obj3),
)
//4。通过寻找是不是继承Array直接判断
//父级元素中的canstructor
console.log(//判断由子元素找回父亲再找回母亲是不是Array
obj1.constructorArray,// obj1.proto.constructorArray,
obj2.constructorArray,
obj3.constructorArray
)
//5.用 ”child instanceof 妈妈“
// 实列
console.log( //孩子(obj) 是妈妈(Array)的孩子吗?(//判断 obj 是不是Array new出来的)
obj1 instanceof Array,
obj2 instanceof Array,
obj3 instanceof Array,
)
//6.输出对象的DNA:内部隐藏属性class
console.log(
Object.prototype.toString.call(obj1),//将obj强行打入顶级父元素去调用顶级父元素的toString()函数
Object.prototype.toString.call(obj2),
Object.prototype.toString.call(obj3)
)
//7 ES5!!!
console.log(
Array.isArray(obj1),
Array.isArray(obj2),
Array.isArray(obj3),
)
//8
console.log(
obj1.constructor.toString(),
obj2.constructor.toString(),
obj3.constructor.toString(),
)
如下:
// console.log(
// obj2.proto==Array.prototype,
// Object.getPrototypeOf(obj2)Array.prototype,
// Array.prototype.isPrototypeOf(obj2),
// obj2.constructorArray,
// obj2 instanceof Array,
// Object.prototype.toString.call(obj2),
// Array.isArray(obj2),
// obj2.constructor.toString()
// )
结果:
true
true
true
true
true
“[object Array]”
true
“function Array() { [native code] }”