Why does the code below print "Tree", "Tree", and not "Bear", "Tree"?
var file_array = new Array(100);
var fileobject = {name: null , folder: null , url: null , modified: null};
fileobject.name = "Bear";
file_array[0] = fileobject;
fileobject.name = "Tree";
file_array[1] = fileobject;
console.log(file_array[0].name);
console.log(file_array[1].name);
-
This question is similar to: JavaScript: assignment to an object within an array changes the value of all objects in the array. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.dumbass– dumbass2026年01月11日 11:07:02 +00:00Commented 12 hours ago
-
Also <stackoverflow.com/q/52663185/3840170>dumbass– dumbass2026年01月11日 11:07:16 +00:00Commented 12 hours ago
1 Answer 1
There's only one object involved. Assigning an object value with = assigns a reference to the object, not a copy.
It's possible to copy objects, but in the general case it can grow to a very hard problem (due to things like reference cycles). If you need lots of those objects, a better solution would be to write a function that returns a fresh object when you call it:
function makeFileObject(name) {
return {name: name , folder: null , url: null , modified: null};
}
file_array[0] = makeFileObject("Bear");
file_array[1] = makeFileObject("Tree");
answered Feb 16, 2017 at 16:09
Pointy
415k62 gold badges600 silver badges633 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Steve
Thanks a lot, been pulling my hair out over this one!
lang-js