将变量传递给函数时,出现“无效参数",但是当我进行硬编码时,它可以在Apps脚本中使用 [英] When passing variable to function I get 'Invalid argument', but when I hard code it works in Apps Script

查看:139
本文介绍了将变量传递给函数时,出现“无效参数",但是当我进行硬编码时,它可以在Apps脚本中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试功能:

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 

解决方法:

  • 使用默认参数:
  • Workarounds:

    • Use 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"
        

        进一步阅读:

        • 范围
        • 关闭
        • 默认参数
        • 吊装
        • 事件对象
        • Further reading:

          • Scope
          • Closures
          • Default parameters
          • Hoisting
          • Event objects
          • 这篇关于将变量传递给函数时,出现“无效参数",但是当我进行硬编码时,它可以在Apps脚本中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆