Ahmad Budi U
Ahmad Budi U

Reputation: 121

How to add multiple objects to an array

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

Upvotes: 4

Views: 1658

Answers (3)

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

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

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68413

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

Upvotes: 1

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22041

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!

Upvotes: 3

Related Questions