我想循环遍历数组中包含的对象,并更改每个对象的属性。如果我这样做:

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j]);

}

控制台应该显示数组中的每个对象,对吧?但实际上它只显示第一个对象。如果我在循环外对数组进行console日志记录,所有的对象都会出现,所以里面肯定有更多的对象。

不管怎样,这是下一个问题。我如何访问,例如Object1。X在数组中,使用循环?

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j.x]);

}

这将返回“undefined”。循环外的控制台日志再次告诉我,所有对象都有“x”的值。如何在循环中访问这些属性?

其他地方建议我为每个属性使用单独的数组,但我想先确保我已经用尽了这个方法。

谢谢你!


当前回答

this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
    console.log(n.name)
}

其他回答

下面是另一种遍历对象数组的方法(您需要在文档中包含jQuery库)。

$.each(array, function(element) {
  // do some operations with each element... 
});

这可能会帮助到某些人。可能是Node中的bug。

var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;

这行不通:

while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined

但这是可行的……

while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.

这也可以……

while ((arr[c]) && (arr[c].name)) { c++; }

但是简单地颠倒顺序是行不通的。我猜这里有某种内部优化破坏了Node。

while ((arr[c].name) && (arr[c])) { c++; }

错误提示数组未定义,但它不是:-/ Node v11.15.0

公认的答案使用正常函数。因此,在forEach上发布相同的代码,并使用箭头函数进行轻微修改

  yourArray.forEach(arrayItem => {
      var x = arrayItem.prop1 + 2;
      console.log(x);
  });

同样是美元。每个你可以使用箭头函数如下

 $.each(array, (item, index) => {
       console.log(index, item);
 });

forEach是一个内置的数组函数。Array.forEach ():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});

可以使用for..of循环遍历对象数组。

for (let item of items) {
    console.log(item); // Will display contents of the object inside the array
}

for..of循环最好的事情之一是,它们可以迭代不止数组。您可以遍历任何类型的可迭代对象,包括映射和对象。如果你需要支持旧的浏览器,请确保你使用了一个transpiler或类似TypeScript的东西。

如果要遍历映射,其语法与上面的基本相同,只是它同时处理键和值。

for (const [key, value] of items) {
  console.log(value);
}

我使用for..of循环进行Javascript中几乎所有类型的迭代。此外,最酷的事情之一是它们也可以与async/await一起工作。