2016-03-14 43 views
0

我希望Google Apps腳本將電子表格中的列名轉換爲列號,但我無法使其與列名稱字符串匹配。請有人告訴我,我能做些什麼才能使它工作。這是我的代碼:爲什麼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; 
    } 
} 

當我運行它查找的列如「要求日期」,這是回來的錯誤:你有內部的throw語句

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

回答

0

for循環。您需要將其移至for循環之外。 現在,您只需在調用throw語句之前測試數組中的第一個值,在本例中爲「Def」。由於'Def'不等於參數columnName,在你的情況下它似乎是'Date Required',它會引發錯誤。

這就是它應該看起來像什麼樣子,如果您傳遞'Date Required'作爲參數,函數現在應該返回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; 
} 
+0

(Facepalm)非常感謝,不敢相信我沒有看到。 –

相關問題