jQuery $.each 用于对象数组中的特定键
jQuery $.each for specific keys within an array of objects
我在下面有这个对象数组,我想用 $.each
进行迭代并获得 type 和 description
Object[
Object {
advert_id=7,
type="entipo",
description="magazine"
},
Object {
advert_id=8,
type="tv",
description="commercials"
}
]
让我们假设它被分配给变量 MyObject
。应该这样做:
$.each(MyObject, function(index){
console.log(MyObject[index].type);
console.log(MyObject[index].description);
});
以上内容比较繁琐。另一种方法如下:
$.each(MyObject, function(index, obj){
console.log(obj.type);
console.log(MyObject[index].description);
});
最后如下:
$.each(MyObject, function(){
console.log(this.type);
console.log(this.description);
});
当然,您可以将 console.log()
替换为您想对这些值执行的任何操作。
您可能想知道为什么不直接使用 this
?您当然可以只使用实现 this
的方法,但使用具有索引和对象的方法的好处是,您可能需要以编程方式对对象的索引位置执行某些操作,其中如果您可以轻松访问它。这并不是说仅使用 this
方法就无法轻松获得它,但它会让生活变得更轻松。
另一种方式:
$(yourArray).each(function(){
console.log(this.type);
console.log(this.description);
);
我在下面有这个对象数组,我想用 $.each
进行迭代并获得 type 和 description
Object[
Object {
advert_id=7,
type="entipo",
description="magazine"
},
Object {
advert_id=8,
type="tv",
description="commercials"
}
]
让我们假设它被分配给变量 MyObject
。应该这样做:
$.each(MyObject, function(index){
console.log(MyObject[index].type);
console.log(MyObject[index].description);
});
以上内容比较繁琐。另一种方法如下:
$.each(MyObject, function(index, obj){
console.log(obj.type);
console.log(MyObject[index].description);
});
最后如下:
$.each(MyObject, function(){
console.log(this.type);
console.log(this.description);
});
当然,您可以将 console.log()
替换为您想对这些值执行的任何操作。
您可能想知道为什么不直接使用 this
?您当然可以只使用实现 this
的方法,但使用具有索引和对象的方法的好处是,您可能需要以编程方式对对象的索引位置执行某些操作,其中如果您可以轻松访问它。这并不是说仅使用 this
方法就无法轻松获得它,但它会让生活变得更轻松。
另一种方式:
$(yourArray).each(function(){
console.log(this.type);
console.log(this.description);
);