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

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

问题描述

这是我的测试函数:

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

当我这样做时它失败了.错误说:INVALID ARGUMENT

但是,如果我将 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 

解决方法:

  • 使用默认参数:
  • //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"
      

      进一步阅读:

      • 范围
      • 闭包
      • 默认参数
      • 提升
      • 事件对象
      • 这篇关于将变量传递给函数时,我得到“无效参数",但是当我对其进行硬编码时,它可以在 Apps 脚本中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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