js 遍历对象的属性的代码

2019-12-24,,,

如:
复制代码 代码如下:
Function.prototype.addMethod=function(methodName,func){
if(!this.prototype[methodName]){
this.prototype[methodName]=func;//给原型增加方法,此方法会影响到该类型的实例上
}
return this.prototype;//返回原型,此类型实例可以进行链形调用
}
function CustomObject(name,value){
this.name=name || 'CustomeObject';
this.value=value || 0;
this.toString=function(){
return '[name:'+this.name+',value:'+this.value+']'
}
}
CustomObject.addMethod('testFun',function(){})
var obj=new CustomObject();
var info='';
for(var property in obj){
info+=property+" | ";
}
alert(info); // name | value | toString | testFun |

但此时for in 也把该对象所继承于prototype对象中的属性也遍历出来了。如果要剔除它所继承的属性,可以用hasOwnProperty语句。如
复制代码 代码如下:
Function.prototype.addMethod=function(methodName,func){
if(!this.prototype[methodName]){
this.prototype[methodName]=func;//给原型增加方法,此方法会影响到该类型的实例上
}
return this.prototype;//返回原型,此类型实例可以进行链形调用
}
function CustomObject(name,value){
this.name=name || 'CustomeObject';
this.value=value || 0;
this.toString=function(){
return '[name:'+this.name+',value:'+this.value+']'
}
}
CustomObject.addMethod('testFun',function(){})
var obj=new CustomObject();
var info='';
for(var property in obj){
if(!obj.hasOwnProperty(property)) continue;
info+=property+" | ";
}
alert(info); // name | value | toString |

您可能感兴趣的文章:

  • js中遍历对象的属性和值的方法
  • Javascript的数组与字典用法与遍历对象的属性技巧
  • jquery动态遍历Json对象的属性和值的方法
  • JS遍历数组和对象的区别及递归遍历对象、数组、属性的方法详解
  • JS遍历页面所有对象属性及实现方法
  • 遍历js中对象的属性和值的实例
  • 遍历json 对象的属性并且动态添加属性的实现
  • JS遍历对象属性的方法示例
  • JavaScript简单遍历DOM对象所有属性的实现方法
  • JS中如何轻松遍历对象属性的方式总结

《js 遍历对象的属性的代码.doc》

下载本文的Word格式文档,以方便收藏与打印。