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);

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

Comments

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();

1 Comment

@AhmadBudiU Glad to help. Accept and upvote the answer that has helped you. meta.stackexchange.com/questions/5234/…
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.