I'm trying to push strings to a 2D array in Google Apps Script but I'm experiencing some weird behaviour I don't understand. A simplified version that produces the same behaviour is here:
function arrayTest() {
var mainArr, subArr, i, arrLoc;
mainArr = [];
subArr = [];
for (i = 0; i < 5; i++) {
mainArr.push(subArr);
}
for (i = 0; i < 10; i++) {
arrLoc = Math.floor(Math.random() * 5);
mainArr[arrLoc].push('test');
}
Logger.log(mainArr);
}
What I would expect is for 'test'
to be pushed into whichever array is at the index the Math functions generate - so if the numbers generated were say 0, 2, 1, 4, 4, 3, 0, 2, 1, 0 I thought I would receive:
[['test', 'test', 'test'], ['test', 'test'], ['test', 'test'], ['test'], ['test', 'test']]
However, this is not the case. What I instead receive is this:
[['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'],
['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'],
['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'],
['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'],
['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test']]
It's clear that 'test'
is being pushed to each position in the mainArr
at each step of the for
loop, rather than just the array that is at the index generated by the Math function.
Is there something blindingly obvious I'm missing here, such as an incorrect operator, or have I misunderstood how arrays work? Some guidance would be muchly appreciated!
Thanks.