问题
I am trying to create a list of tabs based on values in a row, as I have previously done with values in a column (The script here is an example test as I was trying to identify the issue, not the actual script used). However, the forEach()
function is working differently and I do not understand why. Below I will append two sets of scripts and their results.
For column:
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(1,1,5,1);
var STlist = [];
range.getValues().forEach(function(x){
Logger.log(x + " why");
STlist.push(x);
});
Logger.log(STlist);
}
Output for column
[20-02-28 12:10:58:012 HKT] z why
[20-02-28 12:10:58:018 HKT] a why
[20-02-28 12:10:58:021 HKT] b why
[20-02-28 12:10:58:023 HKT] c why
[20-02-28 12:10:58:026 HKT] d why
[20-02-28 12:10:58:029 HKT] [[z], [a], [b], [c], [d]]
For Row
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(1,1,1,5);
var STlist = [];
range.getValues().forEach(function(x){
Logger.log(x + " why");
STlist.push(x);
});
Logger.log(STlist);
}
Output for row
[20-02-28 12:11:35:013 HKT] z,x,d,v,g why
[20-02-28 12:11:35:018 HKT] [[z, x, d, v, g]]
Would it be possible for the row format to work the same as the column format? As I was expecting to see the same results but I got different results.
Thank you
回答1:
To put in spreadsheet terms, the values array always contain rows and each of the rows contain column elements. In both cases,
range.getValues().forEach(function(x){
The x
will be a row. And row will be a array with column elements:
A1:A5: [[z], [a], [b], [c], [d]]
A1:E1: [[z, x, d, v, g]]
A1:A5 has 5 rows and each of those rows contain a column element. So, forEach(row=>)
will iterate 5 rows. A1:E1 contain 1 row and therefore forEach(row=>)
will iterate 1 row. To iterate the elements in each row, you'd need another for-loop:
const arr1 = [["a1","b1"]];
const arr2 = [["a1"],["a2"]];
const arr3 = [["a1","b1"],
["a2","b2"]];
const st = JSON.stringify
const loop_ = (arr) =>
arr.forEach((row, i) =>
row.forEach((colEl, j) =>
console.info(`This array is ${st(arr)}
row is ${st(row)}
Current column is ${st(colEl)}
col Element at index [${i},${j}] in this array is ${colEl}`)));
[arr1,arr2,arr3].forEach(loop_)
References:
- Basic reading
- Related answer
来源:https://stackoverflow.com/questions/60445181/why-does-google-script-for-each-run-differently-for-range-in-a-row-vs-range-in-a