google apps script - Global variable defined in function appears not defined? -



google apps script - Global variable defined in function appears not defined? -

i'm writing script google spreadsheets, want have headers index available globally throughout script.

according theory, should able define global variables within function.

function testfunc() { testvar = 1; // `testvar` global variable }

in code looks more or less this:

function getheaders() { var sheet = spreadsheetapp.getactivesheet(); var info = sheet.getdatarange().getvalues(); var headers = data[0] headeridindex = headers.indexof("id") headernameindex = headers.indexof("first-last") }

however, later on in code, when phone call variable headernameindex, appears undefined:

function tellmenames() { var sheet = spreadsheetapp.getactivesheet(); var info = sheet.getdatarange().getvalues(); (var = 1; < data.length; i++) { logger.log("name: " + data[i][headernameindex]) } }

so doing wrong? thanks.

well, going through some relevant posts on defining global variable in google apps script , this answer turns out can not update global variables within handler function i.e. global variables in gas static.

now, depends on specific utilize case assuming since have defined function getheaders(), want create phone call it, more once. if that's not case, can declare , initialize variables outside scope of functions global variables , read them in other functions.

so might want seek in case (haven't tested next code):

var sheet = spreadsheetapp.getactivesheet(); var info = sheet.getdatarange().getvalues(); var headers = data[0] headeridindex = headers.indexof("id") headernameindex = headers.indexof("first-last") .... function tellmenames() { var sheet = spreadsheetapp.getactivesheet(); var info = sheet.getdatarange().getvalues(); (var = 1; < data.length; i++) { logger.log("name: " + data[i][headernameindex]) } }

if want store , update global variables in handler functions, might want give script-db try. hope gets started in right direction.

google-apps-script google-spreadsheet

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -