Home >Web Front-end >JS Tutorial >Interpret the usage of For, While and recursion in JavaScript_Basic knowledge

Interpret the usage of For, While and recursion in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:34:331470browse

for loop:

Copy code The code is as follows:

for(i=start; i

}


while loop: (Note, if the condition is always true, it will enter an infinite loop and the browser will hang)
Copy code The code is as follows:

while (condition) {
//do something;
//change condition;
}

Recursion:

Use for loop to do substring
Copy code 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


Use recursion to implement substring
Copy code 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 for loop to access object properties:

For arrays and strings, we use index [] to access specific values; for objects, we also use [], but we will use a special variable: propertyName

Copy code 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 a for loop to find the array Data within:
Copy code 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 ) {
                                                                                                                                                  🎜>Person Age City

Sue 22 San Francisco

Joe 45 Halifax

-------------------------------------------------- ----------------------------------

break:

Use break to exit the loop immediately, suitable for for and while loops.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn