这是我的测试功能:
var testFolderId = 'di98kjsdf9...';
function testGetFolder(testFolderId){
folder = DriveApp.getFolderById(testFolderId);
Logger.log("folders: " + folder);
}
当我这样做时它失败了。错误提示:参数无效
但是,如果我将 id 硬编码到“DriveApp.getFolderById”函数中,它就可以工作。
有什么解释吗?这对我来说毫无意义。
当直接从脚本编辑器/菜单/按钮单击/触发器调用函数时,会发生以下操作序列:
-
首先,加载整个脚本并执行所有全局语句。这相当于加载一个网页,其中包含脚本标签中的所有脚本:<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
解决方法:
- Use 默认参数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters:
//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"
进一步阅读:
- Scope https://developer.mozilla.org/en-US/docs/Glossary/Scope
- Closures https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
- 默认参数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
- Hoisting https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
- 事件对象 https://developers.google.com/apps-script/guides/triggers/events
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)