Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  134] [ 2]  / answers: 1 / hits: 21983  / 12 Years ago, wed, january 23, 2013, 12:00:00

Possible Duplicate:

How do I correctly clone a JavaScript object?






I have this code:



var temp = [];
var obj = {name:1};
temp.push(obj);
obj.name = 2;
temp.push(obj);


What I'm expecting to be true:



temp[0].name == 1 && temp[1].name == 2;


What actually happens:



temp[0].name == 2 && temp[1].name == 2;


Why does this happen, and how I can get what I'm expecting?


More From » javascript

 Answers
73

JavaScript arrays hold references to objects, rather than objects themselves. When you push an object into the array it does not create a new object, but it simply puts a reference to the object, that obj also points to, into the array.



So in the end obj, temp[0], and temp1 all point to the same object. To actually create a completely new object, you can use Object.create() or jQuery.extend({},obj). Though in your case it's easy enough just to create a new simple object using var newobj = {name=2}


[#80660] Wednesday, January 23, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiasavannahw

Total Points: 448
Total Questions: 122
Total Answers: 113

Location: Maldives
Member since Tue, Dec 21, 2021
3 Years ago
;