I need help to understand this.
var vectX = [];
var esaminatori = [];
... (code omitted)
vectX = ws.getRange(5, 10, 5, 3).getValues();
for (i = 0; i < 5; i ) {
if (vectX[i][0] != "") {
numEsaminatori ;
esaminatori[numEsaminatori-1] = vectX[i];
};
};
... (code omitted)
for (ii = 0; ii < 5; ii ) {
vectX[ii][3] = " ";
for (i = 0; i < numEsaminatori; i ) {
if (vectX[ii][0] === esaminatori[i][0]) {
vectX[ii][3] = esaminatori[i][3];
i = 6;
};
};
};
ws.getRange(5, 10, 5, 4).setValues(vectX);
The above lines are the only parts of a 230 lines program where appears the array vectX.
Array vectX comes from the spreadsheet and is an array of 5 rows 3 columns, rows may be full of empty, so I copy only the full lines to array esaminatori. In the case I'm testing rows 3 and 5 are empty, rows 1, 2 and 4 have values. So in array esaminatori will be filled rows 0, 1, 2 while in vectX are filled rows 0, 1, 3 and rows 2 and 4 are empty. During the program a new column (index 3) is inserted in array esaminatori, surprisingly the same value in column 3 is added in vectX, but no line of the code makes that. The most incredible is that the value is not inserted randomly, is inserted in the correct [row,column] having in consideration the empty lines.
At the end of the program I want to insert esaminatori column 3 in vectX to write it in the sheet, but not all the lines have values so I initialize the column 3 with a space, otherwise I'll get an error in writing. Now, the strange is that the line that changes the value in vectX[ii][3] automatically changes the corresponding row in esaminatori and lose the content.
So, I could say that in some way the 2 arrays are connected and mirroring themselves.
I have a ghost in my program???
CodePudding user response:
Arrays are assigned by reference not by value. esaminatori[numEsaminatori-1] = vectX[i] assigns the address of the row array of vectX to esaminatori so now vectX and esaminatori share the same address. No ghost.
function test() {
try {
let a = [[1,2,3],[4,5,6],[7,8,9]];
let b = [];
for( let i=0; i<a.length; i ) {
b[i] = a[i];
}
console.log("b before:" b);
for( let i=0; i<b.length; i ) {
b[i][0] = b[i][0] 10;
}
console.log("b after:" b);
console.log("a after:" a);
}
catch(err) {
console.log(err)
}
}
8:56:03 PM Notice Execution started
8:56:04 PM Info b before:1,2,3,4,5,6,7,8,9
8:56:04 PM Info b after:11,2,3,14,5,6,17,8,9
8:56:04 PM Info a after:11,2,3,14,5,6,17,8,9
8:56:04 PM Notice Execution completed