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?
Here are a few methods:
Method 1: use eval
Here is the most direct method:
Disclaimer for the above method: I don’t think this problem is a good candidate for using
eval. If you do useeval, you should never allow user input to go into what you areevaling, or you could open your site to security risks. That mistake is the main reason people sayevalis evil.Method 2: use dynamically generated object properties
This is a much, much better way:
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: