判断一个对象是不是数组类型
判断一个对象是不是数组类型,可以分为判断原型对象,判断构造函数和判断内部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)
)