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

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”的值。如何在循环中访问这些属性?

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

谢谢你!


当前回答

这可能会帮助到某些人。可能是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

其他回答

myArray [j。X]逻辑上是不正确的。

使用(myArray [j]。x);而不是

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].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)
}

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

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

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

 $.each(array, (item, index) => {
       console.log(index, item);
 });
for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}

Const job = [ { 名称:“sipher”, 家庭:“sipherplus”, 工作:“Devops” }, { 名称:“约翰”, 家庭:“母鹿”, 工作:“Devops” }, { 名称:“吉姆”, 家庭:“史密斯”, 工作:“Devops” } ]; Const TXT = ' < ul > ${工作。映射(job => ' <li>${job.name} ${job.name)Family} -> ${job.job}</li> ') .join(")} < / ul >” ; document.body.innerHTML = txt;

小心后面的tick (')