Reputation: 499
I created an array to hold my 3D Objects, but iterating through it to make changes is not working as expected. What is the difference between these two code blocks, and how can I change the for loop accordingly? objects
just holds the 3D objects that are stored with the variable names given in the second code block. I just don't understand how these two would be different.
objects.forEach((obj, index) => {
objects[index] = obj.children[0];
objects[index].angle = 0;
});
versus
sun.angle = 0;
mercury = mercury.children[0];
mercury.angle = 0;
venus = venus.children[0];
venus.angle = 0;
earth = earth.children[0];
earth.angle = 0;
The second code block works here, but the first one does not.
Upvotes: 1
Views: 60
Reputation: 5581
I suspect you're wanting the assignment of objects[index] = obj.children[0]
to change what the variable for the first planet points to, but that's not how object references work. This diagram might help explain:
let moon = { children: [] }
let earth = { children: [ moon ] }
let objects = [ earth ];
In memory this looks like this:
earth --------> { <-------------------+
children: [ |
<ref-moon> -----+ |
} | |
| |
moon ---------> { children: [] } <--+ |
|
objects -----> [ |
<ref-earth> -----------+
]
So earth
is a variable that points to the object in memory, and objects[0]
also points to the same object. If you were to execute the code objects[0] = earth.children[0]
we would end up with this in the diagram:
earth --------> {
children: [
<ref-moon> -----+
} |
/
moon ---------> { children: [] } <-+---+
|
objects -----> [ |
<ref-moon> -----------+
]
You see that earth
still points to the object it originally did, but objects[0]
now points to its child instead. I suspect that you thought that the following would be equivalent but they're not:
The assignment in the first line does not change the variable earth
at all.
This is because each variable (earth, moon, objects) is just a reference to an object in memory. The important thing to understand is the difference between changing a reference and changing the object it refers to. The following code example demonstrates the concept a bit more directly.
let obj1 = { id: 'red' }
let obj2 = { id: 'blue' }
let array = [ obj1, obj2 ]
obj1 = obj2 // now both variables point to blue
console.log('obj1 is blue:', obj1)
console.log('obj2 is blue:', obj2)
console.log('but array still has red:', array)
Upvotes: 1