Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

javascript - 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!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use forEach its a built-in array function. Array.forEach():

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...