JavaScript判断数组还是对象

快乐打工仔 分类:实例代码

判断一个变量的类型,一般使用typeof就可以实现,但是当检测一个变量是Array和Object类型的时候就不好用了,因为无论是数组还是Object对象返回值都是object,例如:

var theObject={webName:"前端教程网",address:"青岛市南区"};
var theArray=["前端教程网","青岛市南区"];
console.log(typeof theObject);//输出object
console.log(typeof theArray);//输出object

以上代码并不能够检测是数组还是对象,所以还得想别的办法。

一.通过length属性判断:

通常情况下数组具有length属性,而对象没有,于是就可以通过此属性判断一个变量是数组还是对象。

代码如下:

var theObject={webName:"前端教程网",address:"青岛市南区"};
var theArray=["前端教程网","青岛市南区"];
var whichType=function(bianliang){ 
  if(typeof bianliang=='object'){ 
    if(typeof bianliang.length=='number'){ 
      return "变量是数组";  
    }
    else{ 
      return '变量是对象';     
    } 
  }
  else{ 
    return "你传入了个什么东西"; 
  } 
}; 
console.log(whichType(theObject));//变量是对象
console.log(whichType(theArray));//变量是数组

以上代码可以判断变量的类型,但是并不完善,因为object对象中完全可以自定义一个length属性。所以代码还是有缺陷的,在某些情况下以上代码并不灵光。

二.使用instanceof方式:

var theObject={webName:"前端教程网",address:"青岛市南区"};
var theArray=["前端教程网","青岛市南区"];
console.log(theArray instanceof Array);//true
console.log(theObject instanceof Array);//false

以上代码可以判断出两者的类型,下面再看一段代码实例:

var theObject={webName:"前端教程网",address:"青岛市南区"};
var theArray=["前端教程网","青岛市南区"];
console.log(theArray instanceof Object);//true
console.log(theObject instanceof Object);//true

因为数组也属于Object,所以都会返回true,所以我们检测的时候要首先检测数组。

三.一个网络上常用的转载方式:

function isArray(obj) {    
  return Object.prototype.toString.call(obj) === '[object Array]';     
}

这个方式比较简略经典,建议使用。

JavaScript判断数组还是对象,这样的场景在实际项目中还是用的比较多的,关于JavaScript判断数组还是对象就介绍到这了。

JavaScript判断数组还是对象属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容