Like other languages, JavaScript has a looping structure and a selection structure.
Select structure:
- if (condition) {
//EXECUTE statement that satisfies the condition
- if (condition) {
//EXECUTE statement that satisfies the condition
} else {
; Execute statement without condition
}
- if (condition 1) {
//EXECUTE statement that satisfies condition 1
} else if (condition 2) {
//Meet Condition 2: N.. The EXECUTE statement
} else{
//EXECUTE statement that does not meet the above conditions
}
- switch (condition) { Case matching result 1:
//Match successful execution statement
& nbsp break; //exit switch
Case matching result 2:
//Match Successful execution statement
& nbsp; break;
....
default: //The above conditions are not successful
//above conditions match unsuccessful execution statement
}
Loop structure:
- For (initial value; number of cycles; self-increment (self-decrement)) {
Loop body
}
<script type= "Text/javascript" >for (var i=0;i<10;i++) { document.write (i + " "); Output results: 0 1 2 3 4 5 6 7 8 9}</script>
- for-in loops, primarily for loop arrays, but not commonly used, because this outputs hidden properties
Specific Use method:
<script type= "Text/javascript" >var array = [1,2,3,4,5,6];var i = 0;for (i in array) { document.write (Array[i] + ' '); i++;} Output is 1 2 3 4 5 6 </script>
The traversal of an array mainly uses a for loop instead of using the for
- While loop
<script type= "Text/javascript" >var array = [1,2,3,4,5,6];var i = 0;while (i<array.length) { document.write (Array[i] + ' '); i++;} Output is 1 2 3 4 5 6 </script>
- Do...while Cycle
<script type= "Text/javascript" >var array = [1,2,3,4,5,6];var i = 0;do{ document.write (array[i] + ' '); i++;} while (i<0);//output result is 1</script>
The difference between the for traversal array and the for-in traversal array
- An array's traversal can only be an indexed array
- the For loop will only iterate through the elements in the array, and for in will traverse the other properties
Such as:<script type= "Text/javascript" >var array = [1,2,3,4,5,6];array.name = ' Zhang San '; for (var i = 0;i<array.length;i++) { C4/>document.write (array[i]+ ' ');} 1 2 3 4 5 6document.write (' <br/> '); var i=0;for (i in array) { document.write (array[i]+ ' '); i++;} 1 2 3 4 5 6 Zhang San </script>
The difference between a while loop and a do...while loop
- The while loop is not looped if the condition is not satisfied
- The Do...while loop is that if the condition is not met, it will still be executed once, as shown in the example above, the initial value of I is 0, does not satisfy the i<0 condition, but still outputs a value
JavaScript loop/Select structure