简体   繁体   中英

Dynamically define variable name and assigning value in Google Apps Script

I`m writing a script to generate a form in Google Apps Script.

The idea is, that the user should select his/her name from a dropdown list, and then be transferred to the question block for him/her.

Although the questions are the same, there are slight changes in the choices if the dropdowns for some of the questions.

I have an array with the names of the users, and I've defined the questions for every single user. This is not ideal, as if there is any change in the questions I have to rewrite every block oone by one.

I want to use a loop which generates the question blocks by creating the variables names using the array of the usernames.

I tried the following (this is not the actual code, but throws the same error)

for (a=0; a < 10; a++)
{
 eval('var beginning'+a);
}

for (b=0;b<10; b++)
{
 eval('beginning' + b) = 1;
}    

The first for loop runs fine, but when I try to assign any value it throws an error. (I use here two for loops for debugging only.) Eg:

 eval('beginning' + b) = 1;  //Throws: We're sorry, a server error occurred. Please wait a bit and try again.
 eval('beginning' + b + '= 1;');  //Throws: We're sorry, a server error occurred. Please wait a bit and try again.
 eval('beginning' + b = 1);  //Throws: Invalid assignment left hand side. (line 1, file "Code")

Using eval like this is also fine: choices = eval('lCountries' + Names[i]).getChoices(); .

How can I assign values to these variables in a for loop?

Thank you very much in advance.

As far as I read up so far, eval() is almost always a bad choice, should be handled with caution and mostly never used. Using dynamic variables in such way is also a bad programming logic. I've never seen a case where it is a must, and your case obviously isn't. You can easily get around it with an object, just define a generic object var myVariables = {} , and then start assigning its properties dynamically for your variables.

var myVariables = {};
myVariables[ "beginning" ] = 1;

for( i = 0; i < 10; i++){
  myVariables[ ("beginning" + i) ] = i;
}


Logger.log( myVariable[ "beginning5" ] ); //Loggs 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM