for()
is a repetitive instruction. It is used when you wish to perform a command several times.
The for()
loop is used when you know how many times the script should run. It has the following syntax:
for(nr_start; condition_nr; nr_increment){ //code to be executed }- 'nr_start' specifies a variable and assigns an initial value to it. It sets up the initial state for the loop.
for()
instruction you can introduce other 'for' or any conditional statements.<script> for(i=0; i<5; i++) { document.write('<br> i = '+i); } </script>
i++
', adds one unit to the value of 'i' with each iteration of the loop.The for…in
loop is less flexible than an ordinary for() loop. This instruction goes through the elements of an object (or an Array) and gets the name (or key) of each property of that object.
for(variable in object){ // instructions }- 'variable' is an index variable that takes the name of the property. For each iteration of the loop, the variable is set to the next property of the object.
<script> var obj = {apple:100, bool:false, astring:'coursesweb.net'}; for(var prop in obj){ document.write(prop + ' - '+ obj[prop]+ '<br>'); } </script>
With 'for...of
' you can parse the properties of an object or the elements of an Array.
The difference from "for...in" is that the for...in keeps in 'variable' the property name (or index for array), but the for...of keeps in 'variable' the property value (or the item value, for array).
for(variable of object){ //code to be executed }- "variable" is a variable that contains the value of the current property (or the item value, for array) from the traversed object.
<script> var arr =['MarPlo.net', 'GamV.eu', 80]; for(var elm of arr){ document.write('<br>'+ elm); } </script>
forEach()
is a JavaScript method used to traverse Array items. forEach
executes a provided function once per array element.
callbackF(val, index, array)
.
val = the element value.
index = the element index.
array = the array being traversed.
<script> var arr = [100, 'marplo.net', 'https://coursesweb.net/']; // callback function function parseArr(val, index) { document.write('['+ index + '] = '+ val +'<br>'); } arr.forEach(parseArr); </script>
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net