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

前端 未结 1 530
故里飘歌
故里飘歌 2020-12-20 07:00

This is my test function:

var testFolderId = \'di98kjsdf9...\';
function testGetFolder(testFolderId){
  folder = DriveApp.getFolderById(testFolderId);
  Logge         


        
1条回答
  •  醉梦人生
    2020-12-20 07:56

    When a function is called directly from the script editor/menu/button click/triggers, the following sequence of actions happens:

    • First, Entire script is loaded and All global statements are executed. This is equivalent to loading a web page with all your script in script tags:

    • The function you called is called. This is like adding callMyFunction() at the bottom of the already loaded script.

    • Except in case of triggers, The function you called is run without passing any arguments. Thus all arguments are undefined

    Caution ⚠️: If the function is called by a trigger, the first parameter passed is usually the event object, while the rest of the parameters 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"
    
    • If global variables are used, Then the arguments should not be declared.
    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

    0 讨论(0)
提交回复
热议问题