繁体   English   中英

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

[英]Why won't Google Apps Script find a string in an array

我希望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;
  }
} 

当我运行它以查找例如“ Date Required”列时,这是返回的错误:

"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"

您在for循环中有throw语句。 您需要将其移至for循环之外。 现在,您仅在调用throw语句之前测试数组中的第一个值,在本例中为“ Def”。 由于“ Def”不等于参数columnName,因此在您的情况下,它似乎是“需要日期”,因此会引发错误。

这就是它的外观,如果您将“需要日期”作为参数传递,则函数现在应返回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;
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM