判断一个对象是否是数组类型的几种方法

判断一个对象是否是数组类型的几种方法

-----判断一个类型是不是数组一共有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.constructor
Array
)
//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.constructor
Array,
// 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] }”

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值