判断Array/Object

Object.prototype.isPrototypeOf()  /  Array.prototype.isPrototypeOf()
if(typeof items === "object"&&!Array.prototype.isPrototypeOf(items)){
  items= [items];
}

constructor属性
if(typeof obj == 'object' && obj.constructor == Array){}

Instanceof

每个对象都有一个constructor属性,它引用了初始化该对象的构造函数,比如判断未知对象的类型,因此我们可以如下写一个方法,代码如下:

if([] instanceof Array){}
if({} instanceof Object){}

猜你喜欢

转载自www.cnblogs.com/hzsll/p/10573868.html