修改现有的表单值-GetChoices()无法正常工作

HDC*_*rus 2 google-apps-script google-forms

为什么“ .getChoices() ”不适用于现有列表项?

我有以下代码,通过它的ID获取表单中的项,并且我打算更新表单项的值。但是,使用.getChoices()方法时,它将失败,并显示错误' TypeError:在对象Item中找不到函数getChoices。'

我获取该项目是一个列表项的要求,并在创建一个列表项,然后取出,它正常工作,如列出的示例代码在这里

我的代码如下:

function getWeekNumberFormItem() {
   var form = FormApp.getActiveForm();
   var item = form.getItemById(12345);//redacted for privacy, but the ID in here is correct. 
   var title = item.getTitle();
   var itemType = item.getType();
   Logger.log('Item Type: ' + itemType);
   Logger.log('Item Title: ' + title);
   var choices = item.getChoices();
   Logger.log(choices);
}
Run Code Online (Sandbox Code Playgroud)

并证明它是一个列表项,我的日志输出是:

在此处输入图片说明

我使用不正确吗?还是只能在Apps脚本创建项目时使用?相反,我将如何在此列表项中获得选择并使用新选项更新它们?我看到其他用户设法做到了这一点,所以我相信这是可能的。

Mog*_*dad 5

Item是一个接口类,提供了一些适用于所有表单项的方法。“接口对象本身很少有用;相反,您通常希望调用Element.asParagraph()之类的方法来将对象转换回精确的类。” 参考

由于.getChoices()是属于ListItem该类且未出现在其中的方法Item,因此需要将其强制转换ItemListItemusing Item.asListItem()

...
var itemType = item.getType();

if (itemType == FormApp.ItemType.LIST) {

  var choices = item.asListItem().getChoices();
  //                 ^^^^^^^^^^^^
}
else throw new Error( "Item is not a List." );
Run Code Online (Sandbox Code Playgroud)