如何用Apps Script处理Google表单响应中的空值/空白
问题分析
报错TypeError: Cannot read property 'getItem' of string的核心原因:当第5个非必填问题未填写时,allQuestions[5]会是undefined(Google表单的getItemResponses()仅返回用户填写过的问题响应),你将其替换为字符串'no answer'后,字符串没有getItem()方法,因此触发错误。
解决方案
先判断allQuestions[5]是否存在,不存在则直接处理空答案场景;存在时再正常执行问题类型、答案的获取逻辑。
修正后的完整代码:
function getAnswer() { var allQuestions, number_of_submissions, itemType5, thisAnswer5, thisQuestion5; number_of_submissions = FormApp.getActiveForm().getResponses().length; // 获取最新提交的所有已填写问题响应 allQuestions = FormApp.getActiveForm().getResponses()[number_of_submissions - 1].getItemResponses(); // 初始化答案为默认值 thisAnswer5 = 'no answer'; thisQuestion5 = allQuestions[5]; // 仅当存在第5个问题的响应时,执行后续逻辑 if (thisQuestion5) { itemType5 = thisQuestion5.getItem().getType(); // 修正原语法错误,判断是否为分页符 if (itemType5 === FormApp.ItemType.PAGE_BREAK) { // 分页逻辑(按需补充) } // 安全获取答案,避免null调用toString() const response = thisQuestion5.getResponse(); thisAnswer5 = response ? response.toString() : 'no answer'; } let htmlMsg = thisAnswer5; if (thisAnswer5 === 'Incident Reported') { GmailApp.sendEmail('abc@gmail.com', 'Incident Reported', '', { htmlBody: htmlMsg }); } };
关键修改点
- 新增
thisQuestion5存在性判断,避免对非对象调用方法 - 对
getResponse()返回值做null校验,防止未填写时触发toString()报错 - 修正原代码语法错误:将
FOR question 5 IF改为标准if语句,= = =改为===,NULL改为小写null - 提前初始化
thisAnswer5为默认值,确保所有场景下变量都有有效值
内容的提问来源于stack exchange,提问作者user6771430
相关产品推荐
相关产品推荐

