简体   繁体   English

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

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

I want Google Apps Script to convert column names in a spreadsheet into column numbers, but I can't get it to match the column name string. 我希望Google Apps脚本将电子表格中的列名转换为列号,但我无法将其与列名字符串匹配。 Please can somebody tell me what I can do to make it work. 请有人告诉我我可以做些什么来使其工作。 This is my code: 这是我的代码:

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;
  }
} 

And when I run it looking for the column 'Date Required' for example, this is the error that comes back: 当我运行它以查找例如“ 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"

You have the throw statement inside the for loop. 您在for循环中有throw语句。 You need to move it outside of the for loop. 您需要将其移至for循环之外。 Now you are only testing the first value in the array, in this case 'Def' before calling the throw statement. 现在,您仅在调用throw语句之前测试数组中的第一个值,在本例中为“ Def”。 Since 'Def' is not equal to the parameter columnName, in your case it seems to be 'Date Required', it throws an error. 由于“ Def”不等于参数columnName,因此在您的情况下,它似乎是“需要日期”,因此会引发错误。

This is what it should look like and the function should now return 1 if you pass in 'Date Required' as a parameter. 这就是它的外观,如果您将“需要日期”作为参数传递,则函数现在应返回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