1

We have variable "a" and we want to create variable "b" as a mirror of "a" variable and then change one of its elements.

Code

function h(){
var a=[[1,2,3]]
var b=a;
b[0][0]="test"
Logger.log(b)
Logger.log(a)
}

Output

[[test,2,3]]
[[test,2,3]]

Why is this happening? Any way to avoid this?

Rubén
  • 34,714
  • 9
  • 70
  • 166

2 Answers2

1

This referes to another question:

Copying array by value in JavaScript

You may test some suggested solutions. I've tested this answer:

https://stackoverflow.com/a/23245968/5372400

The code:

function h(){
  var a=[[1,2,3]];
  var b = JSON.parse(JSON.stringify(a));
  b[0][0]="test";
  Logger.log(b);
  Logger.log(a);
}

result is

[[test, 2, 3]]
[[1.0, 2.0, 3.0]

Looks like, javascript like c does not do array assignments.

Community
  • 1
  • 1
Max Makhrov
  • 17,309
  • 5
  • 55
  • 81
0

You have to deep copy value in array b for this you can use slice method :

arr2 = arr1.slice();

Below is your code with some modifications:

function h(){
var a=[1,2,3];
var b= a.slice();
b[0]="test";
console.log(b);
console.log(a);
}
Ayush
  • 66
  • 3