0

If I create a 2D Array in JavaScript and try to assign one specific object it changes all. Here is my Code:

var a = [0,1];
var b = [];
b.push(a);
b.push(a);
b[0][0]=5;
alert(b[1][0]);

Now I expect to get 0 but I get 5. How can I fix this?

0

3 Answers 3

1

You push the same object reference. by chaging one value, all references shows the changed value. Instead, you could spush a copy of the array by taking Array#slice.

var a = [0, 1];
var b = [];

b.push(a.slice());
b.push(a.slice());

b[0][0] = 5;

console.log(b[1][0]);
console.log(b);

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

Comments

0

you're pushing array which is reference so value at both the index refer to a ( reference to a ) which is why change at any index will reflect on all the other indexes which points to same reference, you need to add value you can see i am using spread syntax for creating a copy of array

b.push([...a]);

var a = [0,1];
var b = [];
b.push(a);
b.push([...a]);
b[0][0]=5;
console.log(b);

Comments

0

By calling b.push(a) twice you are assigning the same array a to the first and second index of b. Therefore if you edit elements of a then it will be reflected for all references of the same instance.

You can perform a deep copy of a to prevent this.

E.g.,

b.push(a.slice());
b.push(a.slice());

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.