簡體   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