为什么Google Apps脚本无法在数组中找到字符串

时间:2016-03-14 16:09:15

标签: javascript arrays string google-apps-script

我希望Google Apps脚本能够将电子表格中的列名转换为列号,但我无法将其与列名字符串相匹配。请有人告诉我我能做些什么才能让它发挥作用。这是我的代码:

function getCol(columnName){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form responses 1");
  var colNames = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
  for (var i = 0; i < colNames.length; i++){
    if (colNames[i].toLowerCase() === columnName.toLowerCase()){
      return i;
    }
  throw "Column name "+columnName+" not found in column names "+colNames;
  }
} 

当我运行它时,查找专栏&#39; Date Required&#39;例如,这是返回的错误:

"Column name Date Required not found in column names Def,Date Required,Day of the week,Rooms Required,Purpose Of Event,No. of attendees,Start Time Required,First Names,Surname,Mobile Number,Email,End Time,House & Street,Area,Town/Postcode,Landline,Mobile 2,Age Group,Date of Previous Bookings if any,How did you hear about SouthBank?,Other Requirements,Other,Catering Provisional Enquiry,Additional Access Time Required?,Set Up Access Time,Length of set up time required,Timestamp,,Booking accepted,Form emailed,Added to calendar"

1 个答案:

答案 0 :(得分:0)

你在for循环中有throw语句。你需要将它移到for循环之外。 现在你只测试数组中的第一个值,在这种情况下&#39; Def&#39;在调用throw语句之前。因为&#39; Def&#39;不等于参数columnName,在您的情况下似乎是&#39; Date Required&#39;,它会抛出错误。

这就是它应该是什么样子,如果你传入“所需日期”,该功能现在应该返回1。作为参数。

function getCol(columnName){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form responses 1");
  var colNames = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
  for (var i = 0; i < colNames.length; i++){
    if (colNames[i].toLowerCase() === columnName.toLowerCase()){
      return i;
    }
  }
  throw "Column name "+columnName+" not found in column names "+colNames;
}