Interpreting the usage of For, While, and recursion in JavaScript _ basic knowledge

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.