亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
While Loop
Task
Do-While Loop
For Loop
任務(wù)
數(shù)組
For-Of 循環(huán)
For-In 循環(huán)
評(píng)論
Home CMS Tutorial WordPress Mastering JavaScript: Part 3, Exploring Loops

Mastering JavaScript: Part 3, Exploring Loops

Aug 28, 2023 pm 10:37 PM

掌握 JavaScript:第 3 部分,探索循環(huán)

Suppose you are tasked with writing a program that displays the numbers 1 to 100. One way to accomplish this is to write 100 console.log() statements. But I'm sure you won't, because you'll get tired of line nine or line ten.

The only part that changes in each statement is the number, so there should be a way to write just one statement. There are also loops. Loops let us repeat a set of steps within a block of code.

  • While Loop
  • Do-While Loop
  • For Loop
  • Array
  • For-Of Loop
  • For-In Loop

While Loop

A While Loop will repeatedly execute a set of statements when some condition evaluates to true. When the condition is false, the program exits the loop. This kind of loop tests a condition before executing the iteration. Iteration is the execution of the loop body. Here is a basic example of a while loop:

let x = 10;

while(x > 0) {
   console.log(`x is now ${x}`);
   x -= 1;
}

console.log("Out of the loop.");

/* Outputs:
x is now 10
x is now 9
x is now 8
x is now 7
x is now 6
x is now 5
x is now 4
x is now 3
x is now 2
x is now 1
Out of the loop. */

In the example above, we first set x to 10. In this example, the condition x > 0 evaluates to true, so the code within the block is executed. This prints the statement "x is now 10" and decrements the value of x by one. During the next check, x equals 9, which is still greater than 0. And so the cycle continues. On the last iteration, x ends up being 1, and we print "x is now 1". Afterwards, x becomes 0, so the condition we are evaluating no longer holds true. Then, we start executing the statements outside the loop and print "Out of theloop".

This is the general form of a while loop:

while (condition) {
    statement;
    statement;
    etc.
}

One thing to remember when using while loops is not to create a never-ending loop. This happens because the condition never becomes false. If it happens to you, your program will crash. Here is an example:

let x = 10;

while(x > 0) {
   console.log(`x is now ${x}`);
   x += 1;
}

console.log("Out of the loop.");

In this case, we are increasing x instead of decreasing it, and the value of x is already greater than 0, so the loop will continue indefinitely.

Task

How many times will this loop be executed?

let i = 0;

while (i < 10) {
    console.log("Hello, World");
    i += 1;
}

Do-While Loop

The do-while loop will execute the statement body first and then check the condition. This kind of loop is useful when you know you want to run the code at least once. The following example will log the value of x once, even though the condition evaluates to false because x is equal to 0.

let x = 0;

do {
   console.log(`x is now ${x}`);
   x -= 1;
} while(x > 0);

console.log("Out of the loop.");

/* Outputs:
x is now 0
Out of the loop. */

I've used do-while loops many times in my own projects to generate random values ??and then continue generating them as long as they don't meet certain conditions. This helps avoid duplication due to initialization and intra-loop reallocation.

This is the general form of a do-while loop:

do {
    statement;
    statement;
    etc.
} while (condition);

Task

Write a do-while loop to display the numbers 1 to 10.

For Loop

The for loop will repeat a block of code a specific number of times. The following example shows the numbers 1 through 10:

for (let i = 1; i <= 10; i++) {
    console.log(i);
}

This is the general form of a for loop:

for (initial; condition; step) {
    statement;
    statement;
    etc.
}

Initial is an expression that sets the value of a variable. This is an optional expression that performs initialization.

Condition is an expression that must be true to execute the statement. The statements within the block are executed only if the condition evaluates to true. Skipping the conditions entirely will cause them to always be true, so you have to exit the loop some other way.

step is an expression that increments the value of a variable. This is also optional and is executed after all statements within the for block have executed. Step expressions are often used near the end condition of a loop.

You can also write a for loop as the equivalent while loop. All you need to do is change your statements and conditions slightly. The for loop above can be rewritten as:

initial;

while(condition) {
    statement;
    statement;
    etc.
    step;
}

One programming pattern is to use a for loop to update the value of a variable with the variable itself and the new value. This example adds the numbers 1 through 10:

let x = 0;

for (let i = 1; i <= 10; i++) {
    x += i;
}

// Outputs: 55
console.log(x);

This is the equivalent while loop which gives the same output:

let x = 0;
let i = 1;

while(i <= 10) {
  x += i;
  i += 1;
}

// Outputs: 55
console.log(x);

You should notice how I increment at the end of the while block instead of at the beginning. Increasing the loop variable i at the beginning would give us 65, which is not what we intend to do here.

The = operator is an assignment operator that adds a value back to a variable. Here is a list of all assignment operators:

操作員 示例 等效
+= x += 2 ?x = x + 2
-= x -= 2 x = x - 2
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
%= x%=2 x = x % 2

任務(wù)

編寫一個(gè) for 循環(huán)來計(jì)算數(shù)字的階乘。數(shù)字n的因子是從1到n的所有整數(shù)的乘積。例如,4! (4 階乘)為 1 x 2 x 3 x 4,等于 24。

數(shù)組

數(shù)組是一個(gè)包含項(xiàng)目列表的對(duì)象,這些項(xiàng)目稱為元素,可以通過索引進(jìn)行訪問。索引是元素在數(shù)組中的位置。第一個(gè)元素位于索引 0 處。

數(shù)組有一個(gè)名為 length 的屬性,它為您提供數(shù)組中元素的總數(shù)。這意味著您可以創(chuàng)建一個(gè) for 循環(huán)來迭代數(shù)組中的項(xiàng)目,如下所示:

let arr = [1, 2, "Hello", "World"];

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

/*
Outputs:
1
2
Hello
World
*/

二維數(shù)組是指元素為數(shù)組的數(shù)組。例如:

let arr = [
    [1, 2],
    ["Hello", "World"]
];

這是循環(huán)數(shù)組并顯示每個(gè)元素的方式:

for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
        console.log(arr[ i ][ j ]);
    }
}

/*
Outputs:
1
2
Hello
World
*/

您將如何重寫上面的循環(huán),以便從末尾開始打印數(shù)組元素?

For-Of 循環(huán)

迭代數(shù)組時(shí)最常見的場(chǎng)景之一是從頭開始,然后一次遍歷所有元素,直到到達(dá)末尾。有一種更短的方法可以將 for 循環(huán)編寫為 for-of 循??環(huán)。

for-of 循??環(huán)讓我們可以循環(huán)遍歷可迭代對(duì)象(例如數(shù)組、映射和字符串)的值。 for-of 循??環(huán)基本上用于迭代對(duì)象的屬性值。這是上一節(jié)中的循環(huán),重寫為 for-of 循??環(huán)。

let arr = [1, 2, "Hello", "World"];

for (let item of arr) {
    console.log(item);
}

/*
Outputs:
1
2
Hello
World
*/

循環(huán)字符串:

let big_word = "Pulchritudinous";

for (let char of big_word) {
    console.log(char);
}

/*
Outputs:
P
u
l
c
h
r
i
t
u
d
i
n
o
u
s
*/

For-In 循環(huán)

這種循環(huán)讓我們可以循環(huán)訪問對(duì)象的屬性。對(duì)象是一種將鍵映射到值的數(shù)據(jù)結(jié)構(gòu)。 JavaScript 中的數(shù)組也是對(duì)象,因此我們也可以使用 for-in 循環(huán)來循環(huán)數(shù)組屬性。我們首先看看如何使用 for-in 循環(huán)來迭代對(duì)象鍵或?qū)傩浴?/p>

以下是使用 for-in 循環(huán)遍歷對(duì)象鍵的示例:

let obj = {
    foo: "Hello",
    bar: "World"
};

for (let key in obj) {
    console.log(key);
}

/*
Outputs:
foo
bar
*/

下面是使用 for-in 循環(huán)遍歷數(shù)組的示例:

let arr = [1, 2, "hello", "world"];

for (let key in arr) {
    console.log(arr[key]);
}

/* Outputs:
1
2
hello
world */

我想補(bǔ)充一點(diǎn),即使我們能夠使用 for-in 循環(huán)遍歷數(shù)組元素,您也應(yīng)該避免這樣做。這是因?yàn)樗哪康氖茄h(huán)訪問對(duì)象的屬性,如果您只想循環(huán)數(shù)組索引來獲取數(shù)組值,則在某些情況下可能會(huì)得到意外的結(jié)果。

評(píng)論

循環(huán)讓我們減少代碼中的重復(fù)。 While 循環(huán)讓我們重復(fù)一個(gè)動(dòng)作,直到條件為假。 do-while 循環(huán)將至少執(zhí)行一次。 For 循環(huán)讓我們重復(fù)一個(gè)動(dòng)作,直到到達(dá)計(jì)數(shù)結(jié)束。 for-in 循環(huán)的設(shè)計(jì)是為了讓我們可以訪問對(duì)象中的鍵。 for-of 循??環(huán)的設(shè)計(jì)是為了讓我們能夠獲取可迭代對(duì)象的值。

在下一部分中,您將學(xué)習(xí)函數(shù)。

本文已根據(jù) Monty Shokeen 的貢獻(xiàn)進(jìn)行了更新。 Monty 是一位全棧開發(fā)人員,他也喜歡編寫教程和學(xué)習(xí)新的 JavaScript 庫。

The above is the detailed content of Mastering JavaScript: Part 3, Exploring Loops. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

How to use the Plugin Check plugin How to use the Plugin Check plugin Jul 04, 2025 am 01:02 AM

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

See all articles