4

why the value of a[0].nil is 400. what should i do to set it to 200. thanks for the answer

a = new Array();
x = new Object();
str = "nil";

x[str] = 200;

a.push(x);

x[str] = 400;

a.push(x);

alert("1 = "+ a[0].nil);
alert("2 = "+ a[1].nil);
Ahmad Budi U
  • 111
  • 1
  • 12

3 Answers3

3

Because you are pushing reference of object x to array a, not copy of that object.

After modifying value of x[str], a[0] reference pointing to updated object.

So in your code a[0],a[1] and xpointing to same object. If you wish to add copy of x object in particular moment of code execution you have to clone your object x and push clone into array.

SO question How do I correctly clone a JavaScript object? will help you in cloning js object. Also see article "JavaScript: Passing by Value or by Reference" to get better idea of variable passing in javascript.

Good Luck!

Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
1

why the value of a[0].nil is 400

Because x still points to old reference which you haven't changed (you only changed value of property inside it).

what should i do to set it to 200

Simply before

x[str] = 400;

add this line

x = {}; //x = new Object();
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • @AhmadBudiU Glad to help. Accept and upvote the answer that has helped you. http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – gurvinder372 May 17 '16 at 10:20
0

You should clone object, with Object.assing as

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

a = new Array();
x = new Object();
str = "nil";

x[str] = 200;

a.push(Object.assign({}, x));

x[str] = 400;

a.push(Object.assign({}, x));

document.write("1 = "+ a[0].nil);
document.write("2 = "+ a[1].nil);
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47