在Google Apps脚本中动态定义变量名称和分配值 [英] Dynamically define variable name and assigning value in Google Apps Script

查看:79
本文介绍了在Google Apps脚本中动态定义变量名称和分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写脚本以在Google Apps脚本中生成表单.

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;
}    

第一个for循环运行良好,但是当我尝试分配任何值时,都会引发错误. (我在这里使用两个for循环仅用于调试.) 例如:

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.) E.g.:

 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")

像这样使用eval也可以:choices = eval('lCountries' + Names[i]).getChoices();.

如何在for循环中为这些变量赋值?

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

非常感谢您.

推荐答案

据我到目前为止所读,eval()几乎总是一个不好的选择,应谨慎处理,并且绝不使用.以这种方式使用动态变量也是不好的编程逻辑.我从未见过必须这样做的情况,而您的情况显然并非如此.您可以轻松地通过一个对象来解决它,只需定义一个通用对象var myVariables = {},然后开始为变量动态分配其属性.

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

这篇关于在Google Apps脚本中动态定义变量名称和分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆