derekantrican derekantrican - 5 months ago 9
Javascript Question

Defining arrays in Google Scripts

I'm a javascript newbie and trying to write a script for a spreadsheet that will pull various things out of it. Right off the bat, I'm having trouble defining an array of names that will be in the spreasheet. The error says "Missing ; before statement (line 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();

// ...
}

Answer

Try this

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()]

You can define arrays simply as follows, instead of allocating and then assigning.

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

Your initial error was because of the following line, and ones like it

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

Since Name is already defined and you are assigning the values to its elements, you should skip the var, so just

Name[0] = Name_cell.getValue();

Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.