Global variable defined in function appears not defined?

后端 未结 2 974
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 04:32

I\'m writing a script for Google Spreadsheets, I want to have my headers index available globally throughout the script.

According to the theory, I should be able to def

相关标签:
2条回答
  • 2021-01-26 05:12

    Well, I was going through some relevant SO posts on defining a global variable in Google Apps Script and from this answer it turns out you can not update global variables inside a handler function i.e. Global Variables in GAS are static.

    Now, it depends on your specific use case but I am assuming since you have defined a function getHeaders(), you would want to make a call to it, more than once. If however that's not the case, then you can simply declare and initialize those variables outside the scope of all functions as global variables and read them in any other functions.

    So you might want to try something like this in your case (haven't tested the following code):

     var sheet = SpreadsheetApp.getActiveSheet();
     var data = sheet.getDataRange().getValues();
     var headers = data[0]
    
     headerIdIndex = headers.indexOf("ID")
     headerNameIndex = headers.indexOf("First-Last")
    
     ....
    
     function tellMeNames() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var data = sheet.getDataRange().getValues();
     for (var i = 1; i < data.length; i++) {
      Logger.log("Name: " + data[i][headerNameIndex])
     }
    }
    

    If however you want to store and update global variables in handler functions, you might want to give Script-DB a try. Hope this gets you started in the right direction.

    0 讨论(0)
  • 2021-01-26 05:23

    I've found a solution I believe, but I'm not sure it is the "proper" way to do this.

    I'm simply defining the global variable above in the script:

    headerNameIndex = SpreadsheetApp.getActiveSheet().getDataRange().getValues()[0].indexOf("First-Last")

    Which seems to work.

    I had wrongly assumed it would only work if it was defined in the onOpen() function.

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