19

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?

asked Jan 23, 2013 at 21:37
1

3 Answers 3

10

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"}

Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answered Jan 23, 2013 at 21:46

Comments

4

JavaScript objects are passed by reference. In your case you have only one object "obj", and temp[0] and temp[1] are pointing to the same object.

answered Jan 23, 2013 at 21:42

Comments

0

obj being an object is added by reference in the array so your actually adding the same obj twice.

Martijn Pieters
1.1m324 gold badges4.2k silver badges3.4k bronze badges
answered Jan 23, 2013 at 21:44

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.