0

I wrote a small script in Google Apps Script that creates an array, and when you press a button it should add "test" to the array, and then print the whole array. So when you press the button for the first time it should display 1 "test". When you press it for the second time it should display the first test plus the new array which should contain 2 "test", so a total of 3 "test". But it doesn't. Somehow when it goes out of the function 'buttonPress' the whole array is deleted or something. Can someone explain this? Thanks!

 var list = new Array;
function doGet() {
  var app = UiApp.createApplication()
  var panel = app.createVerticalPanel().setId('id')
  var button = app.createButton('Button')
  var handler = app.createServerHandler('buttonPress')
  button.addClickHandler(handler)
  app.add(panel)
  panel.add(button)
  return app;
}
function buttonPress(){
list.push('test')
var app = UiApp.getActiveApplication()
var panel  = app.getElementById('id')
var panel2 = app.createVerticalPanel()
var length = list.length
for(var i = 0; i< length; i++){
panel2.add(app.createHTML(list[i]))
}
}

2 Answers 2

1

GAS isn't your everyday Javascript, everytime you hit the buttonPress, the whole code is compiled then executed, just by reading this you already figured, list gets re-instantiated as an empty array.

2 side notes:

UiApp has been deprecated, you must switch to HTMLService.

Arrays in Javascript are better initialized as []. It's the prefered way in all documentations.

Sign up to request clarification or add additional context in comments.

Comments

0

Simply put your function buttonPress() does not know what list even is as you have not declared or defined it inside the function call.

If the code is the exact thing you are running I will note that var list = new Array; at the begging is not reachable by any of the functions.

If you wish, you can use PropertiesService.getScriptProperties().setProperty('name',string) and PropertiesService.getScriptProperties().getProperty('name') to store the array by using JSON.stringify() method and the JSON.parse() to get an array back.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.