如何从数组访问元素?

时间:2018-07-18 13:51:06

标签: arrays google-apps-script google-sheets

var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1Ow_rhF3sibKL3OAQRXpK6LLZDjMOhW-5DKyWWiN5iZg/edit#gid=638513192');
var data = SpreadsheetApp.setActiveSheet(ss.getSheetByName('Graficos'));
Logger.log(SpreadsheetApp.getActiveSpreadsheet());

var ergo = data.getRange(3,2,4,1);//B3:B6 '

我猜想访问这些元素的原因是调用var i = ergo[0];,但这没有用。我必须使用其他语法声明ergo吗?

1 个答案:

答案 0 :(得分:3)

您需要在范围上使用getValues(),这将返回一个二维数组。

var ergo = data.getRange(3,2,4,1).getValues();

此外,由于本质上是在前两行中重复执行操作,因此您的编码效率也不高。看一下这个重构:

function test() {
  var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1Ow_rhF3sibKL3OAQRXpK6LLZDjMOhW-5DKyWWiN5iZg/edit#gid=638513192');
  var data = ss.getSheetByName('Graficos');
  ss.setActiveSheet(data); // There doesn't seem to be a need to do this, so maybe delete this line
  var ergo = data.getRange(3,2,4,1).getValues(); //B3:B6
}