for each element in an array

I am reading a tutorial with the following:

for (var hit in colliders)

This appears to be like a for each element in an array. Is that what this line is doing? Is it looking up the total number of elements in the array colliders[] and assigning that value to the variable hit? If so, is hit an int?


That code in of itself does nothing, it is just looping through the array called colliders (which I'm assuming is a group of colliders). You need code in brackets after that statement in order to put it to use.

for (var hit in colliders)

That code will loop through every object in the array called colliders, and you can refer to each object individually with the new var called hit, and call SendMessage on each one.

To answer your other question, no hit is not an int, it is the same type of whatever kind of objects is in the array called colliders. You may be use to using ints to refer to array indexes, but using this method indexes are no longer necessary.

Sometimes you will of course need to use the old method of for looping so you can track which index you are on and use that int index for other things (like referring to other arrays).

I found the following on w3schools

JavaScript For...In Statement The statement loops through the elements of an array or through the properties of an object.

Syntax for (variable in object) { code to be executed } Looks like this is what's happening in script above. Can anybody confirm?

for (collider in colliders) {
   print (collider.bounds);

gets the same results as

for (i = 0; i < colliders.Length; i++) {
   print (colliders*.bounds);*
*<p>In the case of the for/in loop, the "collider" variable is local to that loop only and doesn't exist outside it.  The second loop doesn't allocate any additional variables.</p>*