7

我是一个 javascript 新手,正在尝试为电子表格编写一个脚本,以便从中提取各种内容。马上,我在定义将在电子表格中的名称数组时遇到了麻烦。错误显示“缺少;语句之前(第 10 行)”

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  //var values = rows.getValues();

  var Names = sheet.getRange("A2:A7");
  var Name = new Array(6);
  var Name_cell = Names.getCell(1, 1);
  var Name[0] = Name_cell.getValue();  //  <-- Here's the issue
  var Name_cell = Names.getCell(2, 1);
  var Name[1] = Name_cell.getValue();
  var Name_cell = Names.getCell(3, 1);
  var Name[2] = Name_cell.getValue();
  var Name_cell = Names.getCell(4, 1);
  var Name[3] = Name_cell.getValue();
  var Name_cell = Names.getCell(5, 1);
  var Name[4] = Name_cell.getValue();
  var Name_cell = Names.getCell(6, 1);
  var Name[5] = Name_cell.getValue();

  // ...
}
4

3 回答 3

8

试试这个

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  //var values = rows.getValues();

  var Names = sheet.getRange("A2:A7");
  var Name = [
    Names.getCell(1, 1).getValue(),
    Names.getCell(2, 1).getValue(),
    .....
    Names.getCell(5, 1).getValue()]

您可以按如下方式简单地定义数组,而不是先分配然后再分配。

var arr = [1,2,3,5]

您最初的错误是由于以下行和类似的

var Name[0] = Name_cell.getValue(); 

由于Name已定义并且您正在为其元素分配值,因此您应该跳过var, 所以只需

Name[0] = Name_cell.getValue();

专业提示:对于大多数问题,比如这个问题,不直接涉及谷歌服务,你最好在谷歌上搜索一下用javascript做的方法。

于 2013-09-03T04:34:17.333 回答
4

I think that maybe it is because you are declaring a variable that you already declared:

var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue();  //  <-- Here's the issue: 'var'

I think this should be like this:

var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();

Tell me if it works! ;)

于 2016-07-06T20:25:34.073 回答
1

这可能对一些像我一样苦苦挣扎的人有所帮助:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];
于 2014-11-10T12:25:11.137 回答