+ 1
How does the for in this code work? What does x represent?
<html> <body> <div id ="demo"> <p>some text</p> <p>some other text</p> </div> <script> var a = document.getElementById("demo"); var arr = a.childNodes; for(var x=0;x<arr.length;x++) { arr[x].innerHTML = "new text"; } </script> </body> </html>
2 odpowiedzi
0
in for cycle, the first element (x) is used to specify the index of array.
array[index];
An example:
var myarray = ["Python", "Java", "Ruby"];
myarray[0]; // Python
myarray[1]; // Java
myarray[2]; // Ruby
SO, WE'VE:
for(var x=0;x<arr.length;x++) {
arr[x].innerHTML = "new text";
/* like write:
arr[0].innerHTML = "new text"; FIRST CYCLE
arr[1].innerHTML = "new text"; SECOND CYCLE because x = x+1
*/
}