javascript Google 电子表格脚本 - 如何转置/旋转多维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16621470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Spreadsheet Script - How to Transpose / Rotate Multi-dimensional Array?
提问by user1488934
I'm trying to create a function that takes in any array and transpose it so that rows turns to columns and columns to rows.
我正在尝试创建一个函数,该函数接受任何数组并将其转置,以便行变为列,列变为行。
Not sure what I've done wrong or missing but keep getting this message once the array is pass through....
不确定我做错了什么或遗漏了什么,但是一旦数组通过,就会继续收到此消息....
TypeError: Cannot set property "0.0" of undefined to "xxxxxx".
类型错误:无法将未定义的属性“0.0”设置为“xxxxxx”。
the error is on line
错误在线
result[row][col] = array[col][row]; // Rotate
结果[行][列] = 数组[列][行]; // 旋转
Any pointer would be much appreciated.
任何指针将不胜感激。
function transposeArray(array){
var result = [];
for(var row = 0; row < array.length; row++){ // Loop over rows
for(var col = 0; col < array[row].length; col++){ // Loop over columns
result[row][col] = array[col][row]; // Rotate
}
}
return result;
}
回答by Mogsdad
回答by AdamL
You will need to initially assign an array object to each element in the outer result array. There might be more efficient ways, but I would be thinking:
您需要最初为外部结果数组中的每个元素分配一个数组对象。可能有更有效的方法,但我会想:
function transposeArray(array){
var result = [];
for (var col = 0; col < array[0].length; col++) { // Loop over array cols
result[col] = [];
for (var row = 0; row < array.length; row++) { // Loop over array rows
result[col][row] = array[row][col]; // Rotate
}
}
return result;
}
回答by Mario Moreno
I have found this way:
我找到了这种方式:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("SEGUNDOA2E");
var notas = sheet.getRange("G6:AK6").getNotes();
for (var i = 0; i < 31; i++){
var nota = notas[0][i];
var conceptos = sheet.getRange(37+i,7).setValue(nota);
}
}
Hope this helps.
希望这可以帮助。
回答by Harold Alberto Bautista Agudel
i solved with request function formula:
我用请求函数公式解决了:
var RanMar = HojaResp.getRange("H1:X1"); // Se establece rango para las marcas de cemento.
var Rango2 = HojaInfo.setActiveCell("B3"); // Temporal
Rango2.setFormula('=transpose(Respuestas!H1:X1)');
Unorthodox, but functional for me.
非正统,但对我来说很实用。
Regards,
问候,
Harold Bautista
哈罗德·包蒂斯塔