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

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

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

谢谢你!


当前回答

Var c = { myProperty:( {name: 'this'}, {name: 'can'}, {name: 'get'}, {name: 'crazy'} ] }; c.myProperty.forEach(函数(myProperty_element) { var x = myProperty_element.name; Console.log('成员的名称是:' + 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

从ES5+开始使用forEach方法真的很简单。您可以直接更改数组中每个对象的每个属性。

myArray.forEach(function (arrayElem){ 
  arrayElem = newPropertyValue;
});

如果你想访问每个对象的特定属性:

myArray.forEach(function (arrayElem){ 
      arrayElem.nameOfYourProperty = newPropertyValue;
    });

数组对象迭代,使用jQuery, (使用第二个参数打印字符串)。

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

公认的答案使用正常函数。因此,在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);
});