判断一个对象是不是数组类型,最全方法

判断一个对象是不是数组类型


判断一个对象是不是数组类型,可以分为判断原型对象,判断构造函数和判断内部class属性三大类,下面代码是所有方法。

// 判断一个对象是不是数组类型
    var a = 10,
        b = 'hello',
        c = true,
        d = null,
        e = undefined;
    var f = function () {};
    var obj1 = {},
        obj2 = [0, 1, 2],
        obj3 = new Date();
    console.log(
        typeof (a),
        typeof (b),
        typeof (c),
        typeof (d),
        typeof (e),
        typeof (f),
        typeof (obj1),
        typeof (obj2),
        typeof (obj3),
    )
    // 改变obj1的原型对象,改变后判断原型对象和判断构造函数方法不再准确
    obj1.__proto__ = Array.prototype;

    // 判断原型对象
    // 1. __proto__获取原型对象,再和数组的原型对象比较。实例对象的__proto__属性指向原型对象。
    console.log(
        obj1.__proto__ == Array.prototype,
        obj2.__proto__ == Array.prototype,
        obj3.__proto__ == Array.prototype
    )
    // 2.Object.getPrototypeOf()函数等效于__proto__属性。返回指定对象的的原型对象
    console.log(
        Object.getPrototypeOf(obj1) == Array.prototype,
        Object.getPrototypeOf(obj2) == Array.prototype,
        Object.getPrototypeOf(obj3) == Array.prototype
    )
    // 3.Object.prototype.isPrototypeOf() 检查一个对象是否存在于另一个对象的原型链中。
    console.log(
        Array.prototype.isPrototypeOf(obj1),
        Array.prototype.isPrototypeOf(obj2),
        Array.prototype.isPrototypeOf(obj3)
    )

    // 判断构造函数
    // 4.用父级原型对象中的constructor属性
    console.log(
        obj1.constructor == Array,
        obj2.constructor == Array,
        obj3.constructor == Array
    )
    // 5.instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。 语法:object instanceof constructor
    console.log(
        obj1 instanceof Array,
        obj2 instanceof Array,
        obj3 instanceof Array
    )

    // 利用顶级父对象的toString()方法判断   最准确
    // 6.Object.prototype.toString.call()
    console.log(
        Object.prototype.toString.call(obj1),
        Object.prototype.toString.call(obj2),
        Object.prototype.toString.call(obj3)
    )
    // 7.es5 Array.isArray()  等效方法6
    console.log(
        Array.isArray(obj1),
        Array.isArray(obj2),
        Array.isArray(obj3)
    )
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值