Google Apps Script:获取Google表单首个问题的最新回复值
解决方案
你之前写的const item = form.getItems()[0];之所以没生效,是因为只拿到了表单的第一个问题对象,既没和最新提交的答案关联,还定义在函数外部完全没被使用。下面是两种可行的修改方案:
方式一:遍历最新提交的响应,取第一个有效问题答案
自动跳过分页符,精准定位表单中第一个有答案的问题:
function getFirstQuestionLastAnswer() { // 打开目标表单 const form = FormApp.openById('your_Form_ID'); const allResponses = form.getResponses(); // 先判断是否存在提交记录 if (allResponses.length === 0) { Logger.log("暂无提交记录"); return null; } // 获取最新的一条提交数据 const latestSubmission = allResponses[allResponses.length - 1]; const allItemResponses = latestSubmission.getItemResponses(); // 遍历问题响应,找到第一个非分页符的答案 for (const itemResp of allItemResponses) { const itemType = itemResp.getItem().getType(); if (itemType !== FormApp.ItemType.PAGE_BREAK) { const firstAnswer = itemResp.getResponse(); Logger.log("首个问题的答案: " + firstAnswer); return firstAnswer; } } // 极端情况:表单所有内容都是分页符 Logger.log("未找到有效问题"); return null; }
方式二:通过表单第一个问题匹配最新提交答案
贴合你最初想用form.getItems()[0]实现的思路,同时处理第一个问题是分页符的情况:
function getFirstQuestionLastAnswer() { const form = FormApp.openById('your_Form_ID'); const firstFormItem = form.getItems()[0]; const allResponses = form.getResponses(); if (allResponses.length === 0) { Logger.log("暂无提交记录"); return null; } const latestSubmission = allResponses[allResponses.length - 1]; // 获取第一个问题对应的提交响应 const firstItemResp = latestSubmission.getItemResponse(firstFormItem); // 如果第一个问题不是分页符,直接返回答案 if (firstItemResp && firstFormItem.getType() !== FormApp.ItemType.PAGE_BREAK) { const firstAnswer = firstItemResp.getResponse(); Logger.log("首个问题的答案: " + firstAnswer); return firstAnswer; } // 若第一个是分页符,遍历找第一个有效问题 const allItemResponses = latestSubmission.getItemResponses(); for (const itemResp of allItemResponses) { const itemType = itemResp.getItem().getType(); if (itemType !== FormApp.ItemType.PAGE_BREAK) { const firstAnswer = itemResp.getResponse(); Logger.log("首个问题的答案: " + firstAnswer); return firstAnswer; } } return null; }
关键修改说明
- 移除了原代码中无用的
const item定义,将表单实例化放在函数内部,避免重复调用FormApp.openById浪费资源 - 增加了无提交记录的判断,防止数组越界报错
- 不再遍历所有问题收集答案,找到第一个有效问题后直接返回,提升运行效率
- 保留分页符判断逻辑,避免误取无效内容
内容的提问来源于stack exchange,提问作者Siva
相关产品推荐
相关产品推荐

