search
HomeCMS TutorialWordPressMastering JavaScript: Part 3, Exploring Loops

掌握 JavaScript:第 3 部分,探索循环

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

任务

编写一个 for 循环来计算数字的阶乘。数字n的因子是从1到n的所有整数的乘积。例如,4! (4 阶乘)为 1 x 2 x 3 x 4,等于 24。

数组

数组是一个包含项目列表的对象,这些项目称为元素,可以通过索引进行访问。索引是元素在数组中的位置。第一个元素位于索引 0 处。

数组有一个名为 length 的属性,它为您提供数组中元素的总数。这意味着您可以创建一个 for 循环来迭代数组中的项目,如下所示:

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

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

/*
Outputs:
1
2
Hello
World
*/

二维数组是指元素为数组的数组。例如:

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

这是循环数组并显示每个元素的方式:

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
*/

您将如何重写上面的循环,以便从末尾开始打印数组元素?

For-Of 循环

迭代数组时最常见的场景之一是从头开始,然后一次遍历所有元素,直到到达末尾。有一种更短的方法可以将 for 循环编写为 for-of 循​​环。

for-of 循​​环让我们可以循环遍历可迭代对象(例如数组、映射和字符串)的值。 for-of 循​​环基本上用于迭代对象的属性值。这是上一节中的循环,重写为 for-of 循​​环。

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

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

/*
Outputs:
1
2
Hello
World
*/

循环字符串:

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 循环

这种循环让我们可以循环访问对象的属性。对象是一种将键映射到值的数据结构。 JavaScript 中的数组也是对象,因此我们也可以使用 for-in 循环来循环数组属性。我们首先看看如何使用 for-in 循环来迭代对象键或属性。

以下是使用 for-in 循环遍历对象键的示例:

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

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

/*
Outputs:
foo
bar
*/

下面是使用 for-in 循环遍历数组的示例:

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

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

/* Outputs:
1
2
hello
world */

我想补充一点,即使我们能够使用 for-in 循环遍历数组元素,您也应该避免这样做。这是因为它的目的是循环访问对象的属性,如果您只想循环数组索引来获取数组值,则在某些情况下可能会得到意外的结果。

评论

循环让我们减少代码中的重复。 While 循环让我们重复一个动作,直到条件为假。 do-while 循环将至少执行一次。 For 循环让我们重复一个动作,直到到达计数结束。 for-in 循环的设计是为了让我们可以访问对象中的键。 for-of 循​​环的设计是为了让我们能够获取可迭代对象的值。

在下一部分中,您将学习函数。

本文已根据 Monty Shokeen 的贡献进行了更新。 Monty 是一位全栈开发人员,他也喜欢编写教程和学习新的 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
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
How does WordPress's plugin ecosystem enhance its CMS capabilities?How does WordPress's plugin ecosystem enhance its CMS capabilities?May 14, 2025 am 12:20 AM

WordPresspluginssignificantlyenhanceitsCMScapabilitiesbyofferingcustomizationandfunctionality.1)Over50,000pluginsallowuserstotailortheirsiteforSEO,e-commerce,andsecurity.2)Pluginscanextendcorefeatures,likeaddingcustomposttypes.3)However,theycancausec

Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.