You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:25:08