For, in method javascript

need help to understanding for in loops in javascript.

I think they mean do this (insert number) times

But then again I haven’t reached that part so idk

1 Like

So the basic concept of for-loops is this, you have a list, or an array, like the one below, then you repeat a piece of code inside it (the for loop) for each item in the array
soldiers = hero.findByType("soldier")
and let’s say we have 3 soldiers, and you want to command each one of them, but instead of specifying the index for each one like this (or maybe using while loops):

hero.command(soldiers[0], "attack", enemy)
hero.command(soldiers[1], "attack", enemy)
hero.command(soldiers[2], "attack", enemy)

you can use a for-in loop:

for soldier in soldiers:
     enemy = soldier.findNearestEnemy()
     if enemy:
          hero.command(soldier, "attack", enemy)

so it repeats the piece of code inside the loop, commanding every soldier you have.

Hope this helps, if you need anything else, you can ask.

Edit: the code above is python

1 Like

thanks 2000 cahrssrsa

1 Like

Anytime (20characters)

This is not a solution and it’s absolutely wrong. At least test it and then google “for in javascript”

I did google it, and i just tried testing it, and i found out that much of my syntax along with other stuff is wrong, i did it the python way, and i was mistaken with how it works in javascript. if you can please correct my code @stormbringer , that was as much as i know, and sorry Haris for the wrong information

For the meantime, i edited the code i posted and made it python, so i wouldn’t be posting false information, and i am researching how for loops work in javascript deeply

I found those two links for the for in loops and the normal for loops, maybe they can clear things out:
for in loop
for loop
Sorry again for the inconvenience


This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.