【问题标题】:How to use Global Variables in Google Apps Script?如何在 Google Apps 脚本中使用全局变量?
【发布时间】:2021-06-13 02:56:55
【问题描述】:

我是 Google Apps 脚本的新手。我在DriveApp.getFolderById 的帮助下定义了locate_file 函数来获取文件夹New York Bike Share 中每个文件的名称。

let folder
let file

function locate_file() {
  folder = DriveApp.getFolderById("162jksCkY98VeQAgnHeAzmnCVbGRKg9rd")
  .getFiles()
  
  while (folder.hasNext())  {
    file = folder.next().getName()

    console.log(file)
  }
}

上面的代码在执行日志中返回下面的结果:

10:47:07 AM Info    201906-citibike-tripdata.csv
10:47:07 AM Info    201905-citibike-tripdata.csv
10:47:07 AM Info    201904-citibike-tripdata.csv
10:47:07 AM Info    201903-citibike-tripdata.csv
10:47:07 AM Info    201902-citibike-tripdata.csv
10:47:07 AM Info    201901-citibike-tripdata.csv
10:47:08 AM Notice  Execution completed

由于我已经定义了全局变量folder,我打算在另一个函数中重用该变量。下面的函数仅用于演示目的,打印出存储在folder 变量中的文件名。失败了。

function check_files()  {
  while (folder.hasNext())  {
    file = folder.next().getName()

    console.log(file)
  }
}
10:53:44 AM Notice  Execution started
10:53:45 AM Error   TypeError: Cannot read property 'hasNext' of undefined
                    check_files @ Code.gs:16

感谢您的帮助。

【问题讨论】:

  • 在你的情况下,check_files()的功能如何执行?
  • @Tanaike 执行 locate_file 我希望变量 folder 存储有一些东西,然后执行 check_files
  • 感谢您的回复。根据您的回复,在 Google Apps Script 中,locate_file 使用脚本编辑器运行后,check_files 使用脚本编辑器运行时,let folderlet file 的值被清除。这样,就会发生这样的错误。而且,即使函数locate_file()check_files()在一次运行中按顺序运行,folderIterator也已经完成。这样,函数check_files() 中的while 循环就不会被使用。 Ref这个请小心。
  • @Tanaike 你能告诉我让它工作的正确方法吗?
  • 感谢您的回复。我提出了一个实现目标的方向。你能确认一下吗?如果这不是您期望的方向,我深表歉意。

标签: google-apps-script global-variables


【解决方案1】:

如果要使用文件夹作为全局变量,在这种情况下,我建议使用文件夹ID作为全局变量。因为folder = DriveApp.getFolderById("###").getFiles()folder 是文件夹迭代器。为此,我认为可以使用 PropertiesService。当这反映到 Google Apps 脚本时,它变成如下。

示例脚本:

// At first, please run this function. By this, the value of "folderId" is stored to PropertiesService.
function setGlobalVariable() {
  const folderId = "162jksCkY98VeQAgnHeAzmnCVbGRKg9rd";
  PropertiesService.getScriptProperties().setProperty("folderId", folderId);
}

// As the next step, please run this function. By this, "folderId" is retrieved from PropertiesService and it is used.
function check_files() {
  const folderId = PropertiesService.getScriptProperties().getProperty("folderId");
  if (folderId) {
    const folder = DriveApp.getFolderById(folderId).getFiles();
    while (folder.hasNext())  {
      file = folder.next().getName();
      console.log(file);
    }
  } else {
    throw new Error("No folder ID.");
  }
}
  • 首先请运行setGlobalVariable()。由此,“folderId”的值被存储到PropertiesService。并且,作为下一步,请运行check_files()。这样,“folderId”就从 PropertiesService 中检索出来并被使用。

  • 如果要更改文件夹ID,请修改setGlobalVariable()并再次运行。

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2019-06-23
    相关资源
    最近更新 更多