Javascript for loops with dynamic variable

73 Views Asked by At

I am writing a Google form using a script so that I can pull the data from a Google spreadsheet and generate a page for each event based on a list of events which are of unknown length.

I have worked out that I can create the pages I need using this loop, with my list of events, eventvalues:

for (var i = 2; i < eventvalues.length; i += 1)
{
    var page = form.addPageBreakItem().setTitle(eventvalues[i][0]);
} 

I would like to end up with variables Page1, Page2, Page3, etc... all the way to eventvalues.length

Currently the variable page is used by the last page only and all others are not assigned to a variable because of being re-assigned.

2

There are 2 best solutions below

0
Andy Hoffman On

You could use an array to store the pages.

var pages = [];

for (var i = 2; i < eventvalues.length; i+=1){
  pages.push(form.addPageBreakItem().setTitle(eventvalues[i][0]));
}
1
Lunny On

You can use the eval function.

    for (var i = 2; i < eventvalues.length; i+=1){
        eval("var page" + i + " = " + form.addPageBreakItem().setTitle(eventvalues[i][0]+";");
   } 
console.log(page1,page2,page3,page4,page5);