javascript遍历对象的属性简单介绍

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

本章节介绍一下如何遍历对象的属性,需要的朋友可以做一下参考。

实现此功能非常的简单,使用for in语句即可实现,但是还是有一些细节需要注意。

先看一段简单代码实例:

var obj={
  webName:"前端教程网",
  url:"pipipi.net",
  age:3
}
for(prop in obj){
  console.log(obj[prop])
}

上面的代码实现了遍历功能,代码非常的简单。

for in语句也可以遍历原型链上的自定义的属性,代码实例如下:

function Antzone(){
  this.webName="前端教程网";
  this.url="pipipi.net";
  this.age=3;
}
Antzone.prototype.address="青岛市南区";
var antzone=new Antzone();
for(prop in antzone){
  console.log(antzone[prop])
}

由此可见,原型链上的自定义属性也是可以遍历的,如果我们只想获取自有属性,那么代码可以改造如下:

function Antzone(){
  this.webName="前端教程网";
  this.url="pipipi.net";
  this.age=3;
}
Antzone.prototype.address="青岛市南区";
var antzone=new Antzone();
for(prop in antzone){
  if(antzone.hasOwnProperty(prop)){
    console.log(antzone[prop])
  }
}

其实使用propertyIsEnumerable()方法也可以实现,更多内容可以参阅相关阅读。

相关阅读:

(1).prototype可以参阅javascript prototype原型一章节。

(2).hasOwnProperty()方法可以参阅javascript hasOwnProperty()一章节。

(3).propertyIsEnumerable()方法可以参阅propertyIsEnumerable()一章节。

回复

我来回复
  • 暂无回复内容