View Full Version : JavaScript help
houssam_ballout
12-11-2006, 05:49 AM
Hello all,
can some body explain, how this code works/ (more on var x)
thanks
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>
the script is creating an array of car names.
To itereate through the array, the scrip uses a for loop, which basically works as moving through each element index in the array, starting at position 0.
var x is just creating a variable, that will be used in the array to store the current array index.
To write the array element, it uses the x to call the array element.
So that script will loop through the array, and write all car names that have been added to the array.
To write a single car name from the array do sommin like:
<script type="text/javascript">
var x = 1;
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
document.write(mycars[x]); // if x is 1, should print Volvo
document.write(mycars[2]); // BMW
</script>
i hope my explanation was useful
vBulletin® v3.6.7, Copyright ©2000-2009, Jelsoft Enterprises Ltd.