【问题标题】:How to stop foreach loop in Google apps script如何在 Google Apps 脚本中停止 foreach 循环
【发布时间】:2021-10-07 08:28:29
【问题描述】:

我需要从 RSS URL 生成一个 docs 文件。

https://cdn.feedcontrol.net/1830/2857-8L5Ntr0N5l5Xf.xml

Tanaike 帮助我在this article 中完成了这项工作。

function myFunction1() {
  const url = "https://cdn.feedcontrol.net/1830/2857-8L5Ntr0N5l5Xf.xml";
  const data = UrlFetchApp.fetch(url).getContentText();
  const root = XmlService.parse(data).getRootElement();
  const ns1 = root.getNamespace();
  const ns2 = XmlService.getNamespace("http://purl.org/rss/1.0/modules/content/");
  root.getChild("channel", ns1).getChildren("item", ns1).forEach(e => {
    Drive.Files.insert({title: e.getChild("title", ns1).getValue(), mimeType: MimeType.GOOGLE_DOCS}, HtmlService.createHtmlOutput(e.getChild("encoded", ns2).getValue()).getBlob());
  });
}

但是,当检索 RSS 中的所有 10 个项目时,它会被复制,因为 RSS 只创建 5 个新项目。 所以我想在第一个项目上创建 DOCs 文件后停止。

请帮帮我!

【问题讨论】:

  • 您要循环 5 个项目还是 1 个项目?如果有 5 项:请改用 for (let i = 0; i < 5; i++) {}。如果是 1 项:您不需要迭代它 const e = root.getChild("channel", ns1).getChild("item", ns1)
  • @idfurw:感谢您的回复!我希望它重复5次。对不起,我的知识水平低,我不知道如何替换。我尝试过这样的事情,但它不起作用。 var e = root.getChild("channel", ns1).getChildren("item", ns1); for (let i = 0; i < 5; i++) { Drive.Files.insert({title: e.getChild("title", ns1).getValue(), "parents": [{'id':folderlocid}], mimeType: MimeType.GOOGLE_DOCS}, HtmlService.createHtmlOutput(e.getChild("encoded", ns2).getValue()).getBlob()); }

标签: google-apps-script google-docs


【解决方案1】:
const items = root.getChild("channel", ns1).getChildren("item", ns1);
for (let i = 0; i < 5; i++) {
  const e = items[i];
  Drive.Files.insert({title: e.getChild("title", ns1).getValue(), "parents": [{'id':folderlocid}], mimeType: MimeType.GOOGLE_DOCS}, HtmlService.createHtmlOutput(e.getChild("encoded", ns2).getValue()).getBlob());
}

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多