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

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

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

谢谢你!


当前回答

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}

其他回答

这里有一个例子,告诉你如何做到这一点:)

Var学生= [{ 名称:“迈克”, 声道:“跟踪”, 成就:23日, 点:400 }, { 名称:“詹姆斯”, 声道:“跟踪”, 成就:2 点:21日 }, ] students.forEach myFunction (); 函数myFunction(item, index) { For (var key in item) { console.log(项目(例子)) } }

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

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(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)
}

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 (')

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}