将变量传递给函数时,出现“无效参数",但是当我进行硬编码时,它可以在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'函数中,它将起作用.
However, if I hardcode the id into the 'DriveApp.getFolderById' function, it works.
有什么解释吗?这对我来说毫无意义.
Any explanation? This makes no sense to me.
推荐答案
直接从脚本编辑器/菜单/按钮单击/触发器调用函数时,将发生以下操作序列:
When a function is called directly from the script editor/menu/button click/triggers, the following sequence of actions happens:
-
首先,加载整个脚本并执行所有全局语句.这等效于用脚本标记中的所有脚本加载网页:
<script>...code.gs..</script>
您调用的函数被调用.这就像在已加载的脚本底部添加callMyFunction()
.
The function you called is called. This is like adding callMyFunction()
at the bottom of the already loaded script.
除非有触发器,否则调用的函数将在不传递任何参数的情况下运行.因此,所有参数都是undefined
Except in case of triggers, The function you called is run without passing any arguments. Thus all arguments are 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
解决方法:
- 使用默认参数:
- Use default parameters:
Workarounds:
//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"