0

I'm using JavaScript in google app script and I'm super confused why there is no simple way to copy stuff by value. I just want a simple way to copy a part of my matrix values2 into the new matrix matrix1. Why is that not possible?

var temp = []; 
for (var t = 0; t<9;t++) {temp[t]= 0;}; //[0,0,0,0,0,0,0,0,0]
var matrix1 = [];
for (var x = 0; x<20;x++) {matrix1[x]=temp;};
for (var x = 0; x < 20; x++) {
  for (var y = 0; y < 9 ; y++) {
    matrix1[x][y] = values2[x+1][y+1];
}};

The code above fills the matrix with identical (last) lines.

1 Answers1

0

Passing array as reference is common among programming languages. In this case, you don't even need temp:

var matrix1 = [];
for (var x = 0; x < 20; x++) {
  matrix1[x] = [];
  for (var y = 0; y < 9; y++) {
    matrix1[x][y] = values2[x + 1][y + 1];
  }
};
Fabricator
  • 12,722
  • 2
  • 27
  • 40