如何通过包含对象的数组循环,并访问他们的属性 [英] 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.
总之,这里的下一个问题。如何访问,例如Object1.x阵列中,使用循环?
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]);
}
这将返回未定义。再次控制台日志外循环告诉我,这些对象都值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.
感谢您!
推荐答案
使用的forEach其内置的数组函数
Use forEach its a built in array function
yourArray.forEach( function (arrayItem)
{
var x = arrayItem.prop1 + 2;
alert(x);
});
这篇关于如何通过包含对象的数组循环,并访问他们的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!