I'm currently facing an issue while attempting to insert strings into a 2D array using Google Apps Script. The behavior I'm encountering is quite peculiar and I'm struggling to comprehend it fully. Below is a simplified version of the code that demonstrates the same behavior:
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);
}
I anticipated that the string 'test'
would be inserted into the array at the index generated by the Math functions. For example, if the generated numbers were 0, 2, 1, 4, 4, 3, 0, 2, 1, 0, my expected output would be:
[['test', 'test', 'test'], ['test', 'test'], ['test', 'test'], ['test'], ['test', 'test']]
However, the actual output differs significantly:
[['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 appears that 'test'
is being added to each position in mainArr
in every iteration of the for
loop, rather than exclusively to the array at the index specified by the Math function.
I'm wondering if I'm overlooking something obvious, like an incorrect operator, or if I have misunderstood the workings of arrays. Any assistance or advice would be greatly appreciated!
Thank you.