This article gives a detailed analysis of the usage of For, While, and recursion in JavaScript. For more information, see
For Loop:
The Code is as follows:
For (I = start; I
}
While loop: (Note: if the condition is always true, it will enter an endless loop, and the browser will drop the hang)
The Code is as follows:
While (condition ){
// Do something;
// Change condition;
}
Recursion:
Substring using the for Loop
The Code is as follows:
Function substring (all, start, end ){
For (I = start; I <= end; I ++ ){
Console. log (all [I]);
}
Substring ("eclipse", 1, 4); // clip
Implement substring recursively
The Code is as follows:
Function substring (all, start, end ){
If (start> = end ){
Return all [start];
}
Else {
Return all [start] + substring (all, start + 1, end );
}
Substring ("eclipse", 1, 4); // clip
Use the for loop to access object attributes:
For arrays and strings, we use index [] to access specific values. For objects, we also use [], but we will use a special variable: propertyName
The Code is as follows:
Var person = {
Name: "Morgan Jones ",
Telephone: "(650) 777-7777 ",
Email: morgan.jones@example.com"
};
For (var propertyName in person ){
Console. log (propertyName + ":" + person [propertyName]);
}
Use the for loop to find the data in the array:
The Code is as follows:
Var table = [
["Person", "Age", "City"],
["Sue", 22, "San Francisco"],
["Joe", 45, "Halifax"]
];
Var I;
Var rows = table. length;
For (r = 0; r Var c;
Var cells = table [r]. length;
Var rowText = "";
For (c = 0; c RowText + = table [r] [c];
If (c <cells-1 ){
RowText + = "";
}
}
Console. log (rowText );
}
Result:
Person Age City
Sue 22 San Francisco
Joe 45 Halifax
--------------------------------------------------------------------------------
Break:
Use break to exit the loop immediately. It is applicable to for and while loops.