修改现有表单值 - GetChoices()不起作用

时间:2015-05-20 20:05:25

标签: google-apps-script google-form

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

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

我正在提取的项目是一个列表项目,当创建列表项然后获取时,它正常工作,如列出的示例代码here

我的代码如下:

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);
}

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

enter image description here

我是否错误地使用了这个,或者只有在Apps脚本创建项目时才能使用它?我将如何获得此列表项中的选项并使用新选项更新它们?我看到其他用户已设法做到这一点,所以我相信这是可能的。

1 个答案:

答案 0 :(得分:4)

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

由于.getChoices()是属于ListItem类的方法,并且未显示在Item中,因此您需要将Item强制转换为ListItem使用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." );