我有一个谷歌表单,提交时调用“on form submit”函数,包括javascript .substring(start,finish)方法。奇怪的是,在我的测试代码中它工作正常但是当它实际上必须使用“提交时”代码实现时,我得到一个错误,说: TypeError:无法调用undefined的方法“substring”。 (第26行,文件“代码”)
这是我的测试代码,它可以正常工作(调用Browser.msgBox)
function test()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; //assumes that sheet containing header columns is first sheet
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var values = SpreadsheetApp.getActiveSheet().getRange(1, 1, 1, lastColumn).getValues();
//variables with form submit data would go here but not for this testing
var dataDump = "\n\n"
var headerValue = values[0][5];
var headerValue5 = headerValue.substring(0,5);
Browser.msgBox(headerValue5);
}
此代码生成错误...
function onFormSubmit(e)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; //assumes that sheet containing header columns is first sheet
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var values = SpreadsheetApp.getActiveSheet().getRange(1, 1, 1, lastColumn).getValues();
//define variables
var timeStamp = e.values[0];
var name = e.values[1];
var email = e.values[2];
var emailSubject = "QMG periodic wRVU responses for ";
emailSubject = emailSubject + timeStamp;
var dataDump = "\n\n";
for (var i = 3; i <= e.values.length; i++)
{
var headerValue = values[0][i];
var responseValue = e.values[i];
var responseValue5 = responseValue.substring(0,5); //error here !!!!!!
i++; //increment i to get detailsValue
var detailsValue = e.values[i];
dataDump = dataDump + headerValue;
dataDump = dataDump + ":\n\n";
dataDump = dataDump + responseValue;
dataDump = dataDump + "\n";
dataDump = dataDump + detailsValue;
dataDump = dataDump + "\n\n*********************\n\n";
}
MailApp.sendEmail(email, emailSubject, dataDump);
}
删除带注释的行“//错误在这里!!!!!!”工作正常,所以我知道它正在读取数组数据。计划是使用.substring()来确定一些格式,以便让它工作。
提前致谢...
答案 0 :(得分:5)
这里没有专业人士,但我认为我对这个问题有所预感。
var array = ["aaa", "bbb", "ccc"];
for (var i = 0; i <= array.length; i++) {
console.log(array[i]);
}
查看运行上述代码时,我会在undefined
,最后得到一个console.log
由于i <= array.length
。
在.substring
上运行undefined
之类的字符串方法会引发错误。
将<=
更改为<
,您应该好好去。