Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - Programmatically setting the name of a variable

Is there a shortcut for writing the following 100 assignments?

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

...

variable_100 = 100;

I have tried

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here are a few methods:

Method 1: use eval

Here is the most direct method:

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

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.

Method 2: use dynamically generated object properties

This is a much, much better way:

// 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.

Method 3: use an array

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...