what is the best way to create a lot of instance? For example if I have class Enemy, and i want to spawn 100 units, should I create loop, and name each in turn differently, or is any easier way to do that? I'm asking about javascript. Thanks
Asked
Active
Viewed 53 times
-1
-
You will find your answer in: https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n. For short, yes, there is nothing wrong to a for loop. Depends on your Enemy constructor (how you want to generate your objects) – azbarcea Sep 27 '19 at 16:40
-
Possible duplicate of [How to create an array containing 1...N](https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n) – Alex Sep 27 '19 at 17:07
1 Answers
0
- The best way is probably a for loop, unless you have some mega-specific stuff going on in the Enemy constructor (in which case you should expand your question because I'm interested). For what you are trying to do I would imagine it would look something like this:
Let firstnames = [list of 10 first names]
Let secondnames = [list of 10 second names]
class Enemy () {
constructor(name) {
this.name = name
}
}
for(let i=0;i==10i++){
for(let j=0, j==10, j++) {
let name = firstname[i].toString+" "+secondname[j].toString
new Enemy(name[i])
}
}
Sidenote: next time you post a question be sure to create a minimal, reproducible example of your code, and tell us what you have tried before :) Check out the "how to ask a question" section of the help section

ipsa scientia potestas
- 483
- 1
- 8
- 23