0

I am stuck with a part of my google script code where one of array elements changed unexpectedly. It looks like a bug to me, but I'd like to hear from here if it's really is or just my coding error that I overlooked. Of course, I'm hoping for a solution as well in any case.

Here is that part of the code.

  if (chkIn) {arr[1] = importData[i][1]+'2';
             } else {

               Logger.log((i)+'   '+importData[i][1]);
               Logger.log((i+1)+'   '+importData[i+1][1]);
               Logger.log((i+2)+'   '+importData[i+2][1]);
               Logger.log(arr[1]);

               arr[1] = importData[i][1]+'1';

               Logger.log('---------------------------------------------------');
               Logger.log((i)+'   '+importData[i][1]);
               Logger.log((i+1)+'   '+importData[i+1][1]);
               Logger.log((i+2)+'   '+importData[i+2][1]);
               Logger.log(arr[1]);
             };

(The if statement doesn't seem relevant here, but I included it just in case.)

Here is the output.

2573   2017122103
2574   20171221041
2575   20171221042
20171221042
---------------------------------------------------
2573   2017122103
2574   20171221041
2575   20171221031
20171221031

I really have no idea how importData[i+2][1] changed its value to arr[1] (the number after 2575).

Thank you in advance.

  • please show what `arr` is? – Jaromanda X Dec 25 '17 at 07:38
  • It's because you are reassigning it here (between logs): `arr[1] = importData[i][1]+'1';` – Kos Dec 25 '17 at 08:05
  • @JaromandaX I use `arr` to store values from `importData` before re-insert it into `importData` (using `splice`). `Logger.log(arr);` gives the following results where some_string are texts I rather not show here. `[Thu Dec 21 00:00:00 GMT+07:00 2017, 20171221042, 100.0, some_string, , , -3383.25, , some_string, some_string]` – Poon Chotchatchawankul Dec 25 '17 at 08:55
  • @Kos My understanding is that the `statement arr[1] = importData[i][1]+'1';` would change the value of `arr[1]`, not `importData[i+2][1]`. Correct me if I'm wrong. – Poon Chotchatchawankul Dec 25 '17 at 09:02
  • @Poon `splice` returns removed items from an array, `slice` returns a copy. Your issue is probably similar to the duplicate question. – Salman A Dec 25 '17 at 10:19
  • @Kos @SalmanA Yeah. I think you're right. I kind of guess it has something to do with `splice` as well, but cannot find any docs that answer this behavior of it (perhaps I didn't know what to look for exactly at the beginning). Sorry for the duplicate. – Poon Chotchatchawankul Dec 25 '17 at 10:43

1 Answers1

0

Probably this is because in your case:

arr === importData[i+2]

So when you change arr[1] you also have changed importData[i+2][1].

Taras Ozarko
  • 16
  • 1
  • 2