将变量传递给函数时,我得到 'Invalid argument',但是当我硬编码时,它在 Apps 脚本中工作

When passing variable to function I get 'Invalid argument', but when I hard code it works in Apps Script

这是我的测试函数:

var testFolderId = 'di98kjsdf9...';
function testGetFolder(testFolderId){
  folder = DriveApp.getFolderById(testFolderId);
  Logger.log("folders: " + folder);
}

我这样做失败了。错误说:无效参数

但是,如果我将 id 硬编码到 'DriveApp.getFolderById' 函数中,它就可以工作。

有什么解释吗?这对我来说毫无意义。

当直接从脚本 editor/menu/button click/triggers 调用函数时,会发生以下操作序列:

  • 首先,加载整个脚本并执行所有全局语句。这相当于在脚本标签中加载所有脚本的网页:<script>...code.gs..</script>

  • 你调用的函数被调用了。这就像在已加载脚本的底部添加 callMyFunction()

  • 除了触发器,你调用的函数是 运行 没有传递任何参数。因此所有参数都是 undefined

注意⚠️:如果函数被触发器调用,传递的第一个参数通常是事件对象,其余参数未定义。

var testFolderId="1dhhddci6";
//When this function is called by IDE, it called without passing any arguments
function testGetFolder(testFolderId){//<=same as calling `testGetFolder()` or `testGetFolder(null)`
  //testFolderId is declared in local scope , but is undefined
  folder = DriveApp.getFolderById(testFolderId);//<= testFolderId is undefined 

解决方法:

//When this function is called by IDE, it called without passing any arguments
function testGetFolder(testFolderId="dhhddci6"){//<=same as calling `testGetFolder()`, but `testFolderId` is passed a value. Also same as calling `testGetFolder("dhhddci6")`
  //testFolderId is declared in local scope and is defined(declared and intialized with a value)
  folder = DriveApp.getFolderById(testFolderId);//<= testFolderId is "dhhddci6"
  • 如果使用全局变量,则不应声明参数。
var testFolderId="1dhhddci6";
//When this function is called by IDE, it called without passing any arguments
function testGetFolder(){//<=same as calling `testGetFolder()`
  //testFolderId is NOT declared in local scope, so variable is looked up in global scope(where it is defined)
  folder = DriveApp.getFolderById(testFolderId);//<= testFolderId is "dhhddci6"

延伸阅读: