How to loop through an array containing objects and access their properties
I want to cycle through the objects contained in an array and change the properties of each one. If I do this:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.
Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?
I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.
Thank you!
使用forEach它的内置数组函数
yourArray.forEach( function (arrayItem)
{
var x = arrayItem.prop1 + 2;
alert(x);
});
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
In ECMAScript 2015 aka ES6, you can use a for..of loop to loop over an array of objects.
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
At the time of posting this answer, support is pretty non-existent for Internet Explorer, but through the use of a transpiler like Traceur or Babel, you can use new Javascript features like this without really having to worry about what browsers support what.
链接地址: http://www.djcxy.com/p/70068.html上一篇: 基于复选框的文本框值被选中/未选中
下一篇: 如何遍历包含对象的数组并访问其属性