以编程方式设置变量的名称 [英] Programmatically setting the name of a variable

查看:164
本文介绍了以编程方式设置变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有编写以下100个作业的快捷方式?

Is there a shortcut for writing the following 100 assignments?

variable_1 = 1;
variable_2 = 2;
variable_3 = 3;

...

variable_100 = 100;

我试过了

for(var i = 1; i <= 100; i++) {
    variable_ + i = i;
}

但是我收到错误消息分配中的左侧无效。有什么想法?

but I get the error message "Invalid left-hand side in assignment". Any ideas?

推荐答案

以下是一些方法:

这是最直接的方法:

for(var i = 1; i <= 100; i++) {
  eval("var variable_" + i + " = " + i);
}
variable_1; // => 1

上述方法的免责声明:我不认为这个问题是使用 eval 的好人选。如果你使用 eval ,你绝不应该允许用户输入进入你的 eval ing,或者您可以打开您的网站以应对安全风险。这个错误是人们说 eval 是邪恶的主要原因。

Disclaimer for the above method: I don't think this problem is a good candidate for using eval. If you do use eval, you should never allow user input to go into what you are evaling, or you could open your site to security risks. That mistake is the main reason people say eval is evil.

这是更多更好的方式:

// If you want these variables to be global, then use `window` (if you're 
// in a browser) instead of your own object.
var obj = {};
for(var i = 1; i <= 100; i++) {
  obj["variable_" + i] = i;
}
obj.variable_1; // => 1

关于使用窗口创建全局变量的注释中的注释:我建议不要这样做,因为它是一种污染全局范围并在不知不觉中踩到变量的快速方法。

About the note in the comment about using window to create global variables: I would recommend against this, as it is a quick way to pollute your global scope and step on variables unwittingly.

David建议使用数组。这是另一个好主意,并且,根据您的尝试,可能是首选:

David suggested using an array. This is another great idea, and, depending on what you are trying to do, may be preferred:

var arr = [];
for(var i = 1; i <= 100; i++) {
  arr.push(i);
}
arr[0]; // => 1

这篇关于以编程方式设置变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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